116

I want to know if it is safe/advisable to convert from ArrayList to Array? I have a text file with each line a string:

1236
1233
4566
4568
....

I want to read them into array list and then i convert it to Array. Is it advisable/legal to do that?

thanks

2
  • 9
    You can, but you haven't given us nearly enough information to tell you whether it's a good idea or not.
    – Jon Skeet
    Commented Nov 1, 2011 at 15:48
  • 6
    ArrayLists's are fine. The only reason I can see for converting to an Array is if you need to call a method that requires it.
    – mike jones
    Commented Nov 1, 2011 at 15:51

10 Answers 10

223

Yes it is safe to convert an ArrayList to an Array. Whether it is a good idea depends on your intended use. Do you need the operations that ArrayList provides? If so, keep it an ArrayList. Else convert away!

ArrayList<Integer> foo = new ArrayList<Integer>();
foo.add(1);
foo.add(1);
foo.add(2);
foo.add(3);
foo.add(5);
Integer[] bar = foo.toArray(new Integer[foo.size()]);
System.out.println("bar.length = " + bar.length);

outputs

bar.length = 5
3
  • What if ArrayList is empty? Commented Dec 10, 2015 at 2:54
  • 1
    The method toArray(T[]) in the type ArrayList<Character> is not applicable for the arguments (char[]) Commented Apr 2, 2018 at 4:28
  • @AaronFranke You are trying to convert non primitive Character to primitive char. In java all arrays are created equal EXCEPT primitive ones. Maybe create and copy the array by hand in a for loop, OR if you like streams you can map to char and then call toCharArray on the stream Commented Aug 22, 2022 at 6:26
75

This is the best way (IMHO).

List<String> myArrayList = new ArrayList<String>();
//.....
String[] myArray = myArrayList.toArray(new String[myArrayList.size()]);

This code works also:

String[] myArray = myArrayList.toArray(new String[0]);

But it less effective: the string array is created twice: first time zero-length array is created, then the real-size array is created, filled and returned. So, if since you know the needed size (from list.size()) you should create array that is big enough to put all elements. In this case it is not re-allocated.

2
5
ArrayList<String> myArrayList = new ArrayList<String>();
...
String[] myArray = myArrayList.toArray(new String[0]);

Whether it's a "good idea" would really be dependent on your use case.

2
  • thanks, just curious to know: i don't need to declare the array size? Commented Nov 1, 2011 at 15:52
  • JavaDocs are your friend. If the array being passed in is too small a new array is returned. The other version of the method that takes no args returns an array of Object Commented Nov 1, 2011 at 15:54
3

assuming v is a ArrayList:

String[] x = (String[]) v.toArray(new String[0]);
0
3

This is the recommended usage for newer Java ( >Java 6)

String[] myArray = myArrayList.toArray(new String[0]);

In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation. This inspection allows to follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).

2

Most answers work as accepted. But since Java 11, there's another way to use toArray() method using method reference operator or double colon operation (::).

Here's an example:

ArrayList<String> list = new ArrayList<>();

// ... add strings to list

// Since java 11    
String[] strArray = list.toArray(String[]::new);


// before java 11, as specified in the official documentation.
strArray = list.toArray(new String[0]);
0
1

I usually use this method.

public static void main(String[] args) {

    ArrayList<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(3);

    int[] arr = list.stream().mapToInt(i -> i).toArray();

    System.out.println(Arrays.toString(arr)); // [1, 2, 3]
}
0

The Collection interface includes the toArray() method to convert a new collection into an array. There are two forms of this method. The no argument version will return the elements of the collection in an Object array: public Object[ ] toArray(). The returned array cannot cast to any other data type. This is the simplest version. The second version requires you to pass in the data type of the array you’d like to return: public Object [ ] toArray(Object type[ ]).

 public static void main(String[] args) {  
           List<String> l=new ArrayList<String>();  
           l.add("A");  
           l.add("B");  
           l.add("C");  
           Object arr[]=l.toArray();  
           for(Object a:arr)  
           {  
                String str=(String)a;  
                System.out.println(str);  
           }  
      }  

for reference, refer this link http://techno-terminal.blogspot.in/2015/11/how-to-obtain-array-from-arraylist.html

0

One approach would be to add the Second for Loop where the printing is being done inside the first for loop. Like this:

static String[] SENTENCE; 

public static void main(String []args) throws Exception{

   Scanner sentence = new Scanner(new File("assets/blah.txt"));
   ArrayList<String> sentenceList = new ArrayList<String>();

   while (sentence.hasNextLine())
   {
       sentenceList.add(sentence.nextLine());
   }

   sentence.close();

   String[] sentenceArray = sentenceList.toArray(new String[sentenceList.size()]);
  // System.out.println(sentenceArray.length);
   for (int r=0;r<sentenceArray.length;r++)
   {
       SENTENCE = sentenceArray[r].split("(?<=[.!?])\\s*"); //split sentences and store in array 

       for (int i=0;i<SENTENCE.length;i++)
       {
           System.out.println("Sentence " + (i+1) + ": " + SENTENCE[i]);
       }
   }    

}
0
ArrayList<String> a = new ArrayList<String>();
a.add( "test" );
@SuppressWarnings( "unused")
Object[] array = a.toArray();

It depends on what you want to achieve if you need to manipulate the array later it would cost more effort than keeping the string in the ArrayList. You have also random access with an ArrayList by list.get( index );

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.