How to convert list to array

Java 11 Certification Practice Questions (For the complete list, refer http://talks.skilltoz.com/java-11-certification-exam-questions/)

How do we convert a list to array?

To convert a list to array, you can use the toArray() method in the Collection interface.

There are two forms of the toArray() method.

Object[] toArray();

This method returns an array containing all of the elements in this collection.

T[] toArray(T[] a);

This method returns an array containing all of the elements in this collection. The runtime type of the returned array is that of the specified array.

Will casting be necessary for the converted array or it’s elements?

The element type of the elements in the Object array returned by the first toArray() method will be Object. Hence, it maybe necessary to cast the Object reference of the elements to the appropriate type, as demonstrated below.

	List<String> strList = Arrays.asList("A", "BC"); 
		Object[] objArray = strList.toArray();
		for (Object obj : objArray) {
			String str = (String) obj;
			System.out.println(str.length());
		}
// Prints 1 and then 2

In the above code, the list strList contains String objects. However, the toArray() method call returns an Object[] containing Object references. In this case, the elements have to be cast to String before we can invoke String API on them.

However, casting the Obect[] to String[] as shown below will cause a ClassCastException as Java runtime cannot be sure that the elements of this Object[] are only String objects.

String[] objArray = (String[])strList.toArray(); // Throws ClassCastException

Using the second form of toArray(), the same method can be rewritten as shown below, eliminating the need for casting.

    List<String> strList = Arrays.asList("A", "BC"); 
    String[] objArray = strList.toArray(new String[0]);
    for (String obj : objArray) {
        String str = obj;
        System.out.println(str.length());
    }

What will happen if the size of the array passed is smaller than that of the list?

If the list fits in the specified array, the same array is returned. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list. Here is an example.

List<Integer> sourceList = Arrays.asList(1, 2, 3, 4, 5);
Integer[] targetArray = sourceList.toArray(new Integer[0]);
System.out.println(Arrays.toString(targetArray));  

In the above example, the toArray() method returns a new array of Integers because the size of the list is greater than that of the array.

Will any change to the list reflect in the array?

No, the array is newly created and it has no relationship to the original List.

List<String> myList = new ArrayList<>();
myList.add("1");
myList.add("2");
Object[] a1 = myList.toArray(new String[2]);
myList.set(0,"3");
System.out.println(Arrays.toString(a1)); // Prints [1, 2]

In the above example, the toArray() method returns a new array of Strings because the array is only a copy of the list. Hence, the changes made to the list do not affect the array.

Quiz

Q1. What is the result of executing this code?

List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2);
Integer[] array1 = { 3,5 };
Integer[] array2 = myList.toArray(array1);
array2[0] = 4;
System.out.println(Arrays.toString(array1));

Leave a Reply

Your email address will not be published. Required fields are marked *