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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With