Why isn't List.toArray() generic? Why must you give the type as an argument (and usually create a new empty instance)?
public Object[] toArray()
http://docs.oracle.com/javase/7/docs/api/java/util/List.html#toArray()
Update: I have since learned that generic array creation is not allowed, but I believe that it should be. Is there any reason why it's not allowed?
Main.java:28: error: generic array creation
T[] ret = new T[size()];
http://ideone.com/3nX0cz
Update: Ok I believe this is the answer:
http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createArrays
Not because it is directly relevant, but indirectly relevant. There is nothing inherently wrong with new T[size()]
, where MyList<String>
would be turned into new String[size()]
, but T could itself be a parameterized type. So if you were to create MyList<Set<Integer>>
, then T
would equal Set<Integer>
and the compiler would try to create new Set<Integer>[size()]
, which could lead to the problem in the link when returned. Someone tried to give an answer along these lines but that answer has since been deleted so I forgot who it was.
If generic array creation were legal, then compiler generated casts would correct the program at compile time but it can fail at runtime, which violates the core fundamental system of generic types.
The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.
As of Java SE 5.0, ArrayList is a generic class with a type parameter. To specify the type of the element objects that the array list holds, you append a class name enclosed in angle brackets, such as ArrayList<Employee>.
The toArray() method is used to get an array which contains all the elements in ArrayList object 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.
This method is supposed to create a new array. But, if you don't have the Class
information of T
, you cannot do that.
You cannot say T[] array = new T[list.size()];
If you pass the array as a parameter (like in the other method) there is no problem.
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