From Arraylist to Array

JavaArraylist

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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.

Solution 3 - Java

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.

Solution 4 - Java

assuming v is a ArrayList:

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

Solution 5 - Java

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

Solution 6 - Java

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

Solution 7 - Java

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]);

Solution 8 - Java

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

Solution 9 - Java

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

Solution 10 - Java

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]);
       }
   }    
   
}

Solution 11 - Java

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]
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEddy FreemanView Question on Stackoverflow
Solution 1 - JavaObscureRobotView Answer on Stackoverflow
Solution 2 - JavaAlexRView Answer on Stackoverflow
Solution 3 - JavaBrian RoachView Answer on Stackoverflow
Solution 4 - JavaErhan BagdemirView Answer on Stackoverflow
Solution 5 - JavaAlexander SavinView Answer on Stackoverflow
Solution 6 - JavamajurageerthanView Answer on Stackoverflow
Solution 7 - JavaHarshitView Answer on Stackoverflow
Solution 8 - JavastackerView Answer on Stackoverflow
Solution 9 - JavasatishView Answer on Stackoverflow
Solution 10 - JavaVipin MenonView Answer on Stackoverflow
Solution 11 - JavadoldolpyView Answer on Stackoverflow