I was working with an implementation of the toArray() in ArrayList and came across a scenario which looks like it's an issue (after checking the behaviour from the apidocs). When we copy an arraylist to an array of smaller size, and then print out the contents of the array, it shows null value for all the entries. I was expecting 1. An exception stating that the destination array cannot accommodate all the elements of the source array, or 2. the array to copy only upto the max index it can from the AL.
Following is the code:
import java.util.ArrayList;
public class TestCollections {
public static void main(String a[]){
ArrayList<String> arrl = new ArrayList<String>();
arrl.add("First");
arrl.add("Second");
arrl.add("Third");
arrl.add("Random");
System.out.println("Actual ArrayList:"+arrl);
String[] strArrActual = new String[arrl.size()];
String[] strArrSmaller = new String[arrl.size()-1];
arrl.toArray(strArrActual);
arrl.toArray(strArrSmaller);
System.out.println("Content of actual sized array:");
for(String str:strArrActual){
System.out.println(str);
}
System.out.println("-----");
System.out.println("Content of smaller sized array:");
System.out.println(strArrSmaller.length);
for(String str:strArrSmaller){
System.out.println(str);
}
}
}
Following is the output:
Actual ArrayList:[First, Second, Third, Random]
Content of actual sized array:
First
Second
Third
Random
-----
Content of smaller sized array:
3
null
null
null
Where am I going wrong?