Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does List.toArray() return an array of Object? [duplicate]

Possible Duplicate:
why does List<String>.toArray() return Object[] and not String[]? how to work around this?

See this code example :

    List<String> list = new ArrayList<String>();
    list.add("hello");
    list.add("world");
    Object [] array = list.toArray();

Why does the method toArray() return an array of Object ? Other List methods such as get() , remove() are able to return the type of objects in the list.

like image 710
Arnaud Avatar asked Jun 13 '12 03:06

Arnaud


People also ask

Does toArray create a copy?

ToArray which in turn creates copy of elements (optimized for ICollection and hence Array[] , but still making copy) with internal Buffer class.

What does toArray return in Java?

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


1 Answers

Because array has been in Java since the beginning, while generics
were only introduced in Java 5. And the List.toArray() method was 
introduced in Java 1.2, before generics existed, so it was
specified to return Object[].

u can use toArray(T[] a) just take a look Collection.toArray(T[] a)

like image 58
Sumit Singh Avatar answered Oct 17 '22 01:10

Sumit Singh