Two reasons I can think of:
- Erasure means that the generic parameters aren't available at runtime, so an
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. - The way the method is defined means that you can pass in a reference to an existing array, and have this populated via the method. In some cases this is likely very convenient, rather than having a new array returned and then copying its values elsewhere.
arrays - ArrayList.toArray() method in Java - Stack Overflow
Why does toArray method of arraylist class returns Object[] and not the provided type array
does .toArray() both return and modify the arraylist to a specific array?
New Collection.toArray(IntFunction) Default Method in JDK 11 EA build 22
Videos
Two reasons I can think of:
- Erasure means that the generic parameters aren't available at runtime, so an
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. - The way the method is defined means that you can pass in a reference to an existing array, and have this populated via the method. In some cases this is likely very convenient, rather than having a new array returned and then copying its values elsewhere.
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.
Eg ArrayList<Integer> should return Interger[] instead of Object[]
Is it being of java's generics
Does toArray method require us to assign it to the var we're turning it into with an equal sign, or does it work just the same without assigning it to it? In short, are there any differences between these two codes? :
groceryList.getGroceryList().toArray(myArray);
myArray = groceryList.getGroceryList().toArray(myArray);