Conversion between Array and List types

In some cases, we may need to convert an array to a list or vice versa. The method asList() is available in the Arrays class, and the toArray() method in list and set classes serve this purpose.

also read:

The Arrays.asList() method converts an array into a list and the size of the list is fixed. Let us see a sample of how the asList() method works,

Integer[] numArr = {100, 200, 300, 400, 500};
List<integer> numList = Arrays.asList(numArr);
System.out.println("size of list is : " + numList.size());
System.out.println("elements in list : " + numList);
numList.set(3,600); // Update the 4th element in list
System.out.println("After update, elements in list : " + numList);
System.out.println("4th element in list is : " + numList.get(3));
System.out.println("4th element in array is : " + numArr[3]);

The output of the above code is,

size of list is : 5
elements in list : [100, 200, 300, 400, 500]
After update, elements in list : [100, 200, 300, 600, 500]
4th element in list is : 600
4th element in array is : 600

In the above example, we saw that the array numArr is converted to a list numList which is of the same size as the array. We also note that any further changes in the list numList have updated the array numArr also.

The toArray() method converts a set or list to an array. This method has two forms of invocation. One form of the toArray() method returns a Object array, and another form returns the array of the type that is passed as the argument. Let us see the following code to know how the toArray() method works,

Set<string> langSet = new HashSet<string>();
System.out.println("size of the set : " + langSet.size());
Object[] langArr  = langSet.toArray(); // this returns an object array
System.out.println("length of array langArr : " + langArr.length);
String[] arr2 = new String[5];
arr2 = langSet.toArray(arr2); // this returns an array of same type as arr2 i.e a String array
System.out.println("length of array arr2 : " + arr2.length);
System.out.print("elements in array arr2 : ");
for(String str : arr2)
    System.out.print(str + " ");

The output of the above code is,

size of the set : 5
length of array langArr : 5
length of array arr2 : 5
elements in array arr2 : Java C++ C Perl Sql



About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.