Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't List.toArray() generic?

Tags:

java

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.

like image 558
Chloe Avatar asked Oct 15 '13 18:10

Chloe


People also ask

Why are there no generic arrays in Java?

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.

What is the use of toArray () in Java?

The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.

Can you create an ArrayList of a generic type?

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>.

How do you use the toArray method?

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.


1 Answers

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.

like image 54
Camouflage Avatar answered Oct 29 '22 17:10

Camouflage