115

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

ziu
  • 2,634
  • 2
  • 24
  • 39
Eddy Freeman
  • 3,207
  • 6
  • 35
  • 55
  • 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 Nov 01 '11 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 Nov 01 '11 at 15:51

11 Answers11

222

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
lgvalle
  • 3,712
  • 1
  • 19
  • 14
ObscureRobot
  • 7,306
  • 2
  • 27
  • 36
  • What if ArrayList is empty? – ThanosFisherman Dec 10 '15 at 02:54
  • 1
    `The method toArray(T[]) in the type ArrayList is not applicable for the arguments (char[])` – Aaron Franke Apr 02 '18 at 04: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 – DownloadPizza Aug 22 '22 at 06: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.

Nissa
  • 4,636
  • 8
  • 29
  • 37
AlexR
  • 114,158
  • 16
  • 130
  • 208
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.

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
  • thanks, just curious to know: i don't need to declare the array size? – Eddy Freeman Nov 01 '11 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` – Brian Roach Nov 01 '11 at 15:54
3

assuming v is a ArrayList:

String[] x = (String[]) v.toArray(new String[0]);
Erhan Bagdemir
  • 5,231
  • 6
  • 34
  • 40
1

There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.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. You can 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).

Alexander Savin
  • 1,952
  • 1
  • 15
  • 30
1

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).

majurageerthan
  • 2,169
  • 3
  • 17
  • 30
1

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]);
Harshit
  • 617
  • 1
  • 6
  • 15
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

satish
  • 1,571
  • 1
  • 11
  • 4
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]);
       }
   }    

}
Vipin Menon
  • 2,892
  • 4
  • 20
  • 35
0

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]
}
kyeahen
  • 161
  • 8
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 );

stacker
  • 68,052
  • 28
  • 140
  • 210