public class ToArrayTest {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
//what happens here??, since I have allocated new String[0] for single element, will it return single element or all elements ??
String[] array = arrayList.toArray(new String[0]);
System.out.println(array.length);
}
}
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
//what happens here??, since I have allocated new String[0] for single element, will it return single element or all elements ??
String[] array = arrayList.toArray(new String[0]);
System.out.println(array.length);
}
}
Output: 4
As per spec, it's going to create a new array, if it does not fit in.
Returns an array containing all of the elements in this list in proper
sequence (from first to last element); the runtime type of the returned array is
that of the specified array. If the list fits in the specified array, it is
returned therein. Otherwise, a new array is allocated with the runtime type of
the specified array and the size of this list.