Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting 'ArrayList<String> to 'String[]' in Java

How might I convert an ArrayList<String> object to a String[] array in Java?

like image 876
Alex Avatar asked Oct 28 '10 11:10

Alex


People also ask

How do you convert an ArrayList to a String in java?

To convert the contents of an ArrayList to a String, create a StringBuffer object append the contents of the ArrayList to it, finally convert the StringBuffer object to String using the toString() method.

How do I convert a list to a String in java?

We can use StringBuilder class to convert List to String. StringBuilder is the best approach if you have other than String Array, List. We can add elements in the object of StringBuilder using the append() method while looping and then convert it into string using toString() method of String class at the end.

How do you concatenate an ArrayList element in java?

Approach: ArrayLists can be joined in Java with the help of Collection. addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.


1 Answers

List<String> list = ..; String[] array = list.toArray(new String[0]); 

For example:

List<String> list = new ArrayList<String>(); //add some stuff list.add("android"); list.add("apple"); String[] stringArray = list.toArray(new String[0]); 

The toArray() method without passing any argument returns Object[]. So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.

Important update: Originally the code above used new String[list.size()]. However, this blogpost reveals that due to JVM optimizations, using new String[0] is better now.

like image 91
Bozho Avatar answered Sep 20 '22 15:09

Bozho