2

For example:

List<String> items = new ArrayList<String>();
String[] aItems = items.toArray(); // type error, because toArray() returns Object[]

I understand that this is the way it is, and it cannot be changed. Of course I can cast it to String[], but I wonder what is the idea behind it? Is this a "bug" in Java, or is there a good reason for it?

0

1 Answer 1

6

Flexibility.

The toArray() method without passing any argument returns Object[].

There is a good reason that now you know which type you are expecting and the authors of the method do not know which type of array to return at runtime due to type erasing. So they just let it be the Super type of all the object which is Object and that is why it returns Object[]

If you want to specify your type, they are good and return your specific type :)

String[] aItems= items.toArray(new String[0]);
Sign up to request clarification or add additional context in comments.

3 Comments

Better use items.toArray(new String[items.size()]) to prevent allocation of additional array object. If array size is equal to List size then items elements will be copied to the given array and method returns that array, not the newly created array.
I still don't see why can't List<T>().toArray() return T[] ? I don't see how it would be possible to return anything else.
Oh I see now. You just can't declare it that way. Well, I don't see it as a good reason. I see it as a language barrier.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.