I am wondering why did they design the toArray method in ArrayList to take a input of an array in Java?
ArrayList<String> listArray = new ArrayList<String>();
listArray.add("Germany");
listArray.add("Holland");
listArray.add("Sweden");
String []strArray = new String[3];
String[] a = (String [])listArray.toArray(strArray);
To me it appears that, they dont need this input because the instance of the ArrayList itself has enough details to convert the data into an array.
My question is why do they still need the array to be passed in? Thanks.
Two reasons I can think of:
ArrayList<String>doesn’t know that it contains strings, it’s just the raw typeArrayList. Thus all invocations oftoArray()would have to return anObject[], which isn’t strictly correct. You’d have to actually create a second array ofString[]then iterate over the first, casting all of its parameters in turn to come out with the desired result type.