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
source
share