Different ways to convert list to array

This post explains two ways through which we can convert a list to array.

First approach is simply calling toArrayList on list instance. This method returns an Object array,

When converting to array it doesn’t consider the data type of the entries in the list. Below is the code snippet

list.toArray();

The second approach involves calling overloaded method named toArrayList which takes an array instance as parameter.

The purpose of parameter is to tell java the type of array to be returned as result of the method call. Below is the code snippet.

list.toArray(new Integer[0]);

This tells the java to return an array of type Integer.

Below is the complete code

Main code


1  package Core.Collection;
2  
3  import java.util.ArrayList;
4  import java.util.List;
5  
6  public class CollectionDemo1 {
7   public static void main(String[] args) {
8       List list = new ArrayList();
9       list.add(1);
10      list.add(2);
11      list.add(3);
12      list.add(4);
13      list.add(5);
14      
15      Object[] array1 = list.toArray();
16      for(Object value : array1) {
17          Integer intValue = (Integer)value;
18          System.out.println(intValue);
19      }
20      
21      System.out.println();
22      
23      Integer[] array2 = list.toArray(new Integer[0]);
24      for(Integer value : array2) {
25          System.out.println(value);
26      }
27  }
28 }

The advantage with the second approach when compared to first approach is that we can avoid casting each entry to appropriate datatype when looping through the array elements.

As shown in the code line 16 to 18, with the first approach we need to cast each entry to appropriate datatype before processing.

But with the second approach as shown in code line 24 to 26, we don’t need to cast each entry to appropriate datatype.

Output

1
2
3
4
5

1
2
3
4
5

Leave a Reply