Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between converting List to Array

I was just wondering what is the difference between following two approach of converting List to Array.

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 one :

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's size

I got the same output for testarray on console.

like image 807
Vimal Bera Avatar asked Dec 19 '22 03:12

Vimal Bera


1 Answers

public <T> T[] toArray(T[] a)

a - This is the array into which the elements of the list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose. So in first case a new array is being created while in second case, it is using the same array.

Sample Code :

Case -1 : array being passed can hold elements of list

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 : Array being passed cannot hold elements of list

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
like image 103
Ouney Avatar answered Jan 04 '23 18:01

Ouney