With Java, putting contents of an Array into a new List object or adding into an existing List object can be achieved easily using a for() loop; just by going through each and every element in array and adding to List one at a time. But that is not needed. Java has provided a method to achieve that easily; just with one method call. Following code snippet shows how.//import java.util.List;
//import java.util.Arrays;
String[] array = {"one", "two", "three"};
List newListObject = Arrays.asList(array);
//adding to existing List
String[] newArray = {"four", "five"};
newListObject.addAll(Arrays.asList(newArray));
//import java.util.Arrays;
String[] array = {"one", "two", "three"};
List newListObject = Arrays.asList(array);
//adding to existing List
String[] newArray = {"four", "five"};
newListObject.addAll(Arrays.asList(newArray));
Also creating a new Array object using an existing List object can be done using another for() loop; by creating a new Array object with a size matching to list size and adding each on at a time. But for this requirement, there are a set of methods.
List list = new ArrayList();
list.add("one");
list.add("two");
Object[] array1 = list.toArray(); //1
String[] array2 = list.toArray(new String[0]); //2
String[] array3 = new String[2];
list.toArray(array3); //3
list.add("one");
list.add("two");
Object[] array1 = list.toArray(); //1
String[] array2 = list.toArray(new String[0]); //2
String[] array3 = new String[2];
list.toArray(array3); //3
With Line #1, returned array is of Object type, while #2 returns a new array object of String type.
Line #3 uses the same method used in #2, but in this case we have provided an array object with the same size as the list. Because of that in line #3, the provided array object is populated with list elements.
Translate into your language
Reader Comments
Search More Articles

Kamal Mettananada is a Software Architect, Java Explorer and Blogger. Digizol consists of computer related articles, tutorials, tips and other information.
any criticism is appreciated.
The article explains how to convert a list into an array. Hasn't it solve your problem? Can you details your issue?
1) String[] array2 = list.toArray(new String[0]); //2
does not compile, I have to change it to :
String[] array2 = (String[]) list.toArray(new String[0]); //2
to be able to compile.
2) And then on run I got an UnsupportedOperationException on line:
newListObject.addAll(Arrays.asList(newArray));
Too bad I m struggeling with these array and list and can't find anyway to fix it.
how to connect the given array to list
Post a Comment
We appreciate your opinions, suggestions and criticism.