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.
The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.
Set toArray() method in Java with Example If we provide the type of Object array we want we can pass it as an argument. for ex: set. toArray(new Integer[0]) returns an array of type Integer, we can also do it as set. toArray(new Integer[size]) where size is the size of the resultant array.
Vector and ArrayList don't have a load factor.
Two reasons I can think of:
ArrayList<String>
doesn't know that it contains strings, it's just the raw type ArrayList
. Thus all invocations of toArray()
would have to return an Object[]
, which isn't strictly correct. You'd have to actually create a second array of String[]
then iterate over the first, casting all of its parameters in turn to come out with the desired result type.In your code, the ArrayList
can contain anything, not only Strings. You could rewrite the code to:
ArrayList<String> listArray = new ArrayList<String>();
listArray.add("Germany");
listArray.add("Holland");
listArray.add("Sweden");
String []strArray = new String[3];
String[] a = listArray.toArray(strArray);
However, in Java arrays contain their content type (String) at runtime, while generics are erased by the compiler, so there is still no way for the runtime system to know that it should create a String[]
in your code.
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