The difference between converting a list to an array

I'm just wondering what the difference is between the following two approaches to List to Array conversion.

List<String> test = new ArrayList<String>();
test.add("AB");
test.add("BC");
test.add("CD");
test.add("DE");
test.add("EF");

String[] testarray = test.toArray(new String[0]); // passing 0 as Array size

And below:

List<String> test = new ArrayList<String>();
test.add("AB");
test.add("BC");
test.add("CD");
test.add("DE");
test.add("EF");

String[] testarray = test.toArray(new String[test.size()]); // passing list size

I got the same result for testarray on the console.

+4
source share
1 answer
public <T> T[] toArray(T[] a)

a is the array into which the list items should be stored, if it is large enough; otherwise, a new array of the same runtime type is allocated for this purpose. Therefore, in the first case, a new array is created, in the second case, it uses the same array.

Code example:

Case -1: the passed array may contain list items

public static void main(String[] args) {
        List<String> test = new ArrayList<String>();
        test.add("AB");
        test.add("BC");
        test.add("CD");
        test.add("DE");
        test.add("EF");
        String[] s= new String[10];
        String[] testarray = test.toArray(s); 
        System.out.println(s==testarray);
    }

O/P :

true

Case-2: the transferred array cannot contain list items

public static void main(String[] args) {
        List<String> test = new ArrayList<String>();
        test.add("AB");
        test.add("BC");
        test.add("CD");
        test.add("DE");
        test.add("EF");
        String[] s= new String[0];
        String[] testarray = test.toArray(s); 
        System.out.println(s==testarray);

    }

O/P :

false
+11
source

All Articles