Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no toArray(Class<T>)?

Why is there no toArray variant in List which only accepts a type, for example:

Foo[] array = list.toArray(Foo.class);
// or
Foo[] array = list.toArray(Foo[].class);

I have seen

// existing array
Foo[] array = list.toArray(array);
// Fake array
Foo[] array = list.toArray(new Foo[0]);

But it seems inefficient and counter-intuitive to me to create an empty array when I just want to specify the type and not create an unecessary throw-away array.

like image 916
james_t Avatar asked Jul 31 '19 17:07

james_t


People also ask

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.

Is toArray deterministic in Java?

toArray() will produce the same ordering for equal sets, but you cannot rely on this. Nor can you rely on the order from an iterator. Sets are completely and wholly unordered.


1 Answers

From an interface-perspective, I agree.

The method only needs the type (apart from the side-effects), so it would be appropriate to only demand the type.

The main reason is efficiency, I guess. The implementation that only takes the type is significantly slower, I did not check the implementation details though (see the benchmarks in .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])? and the blog Arrays of Wisdom of the Ancients).

However, note that we got a new variant since Java 11 which comes closer to what you want and is also more appropriate in this situation:

toArray(Foo[]::new)

From its documentation:

Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.

Use toArray() to create an array whose runtime type is Object[], or use toArray(T[]) to reuse an existing array.

The default implementation calls the generator function with zero and then passes the resulting array to toArray(T[]).

The method does not need reflection since you provide the generator directly.

To summarize, nowadays you should use

  • toArray() if you want Object[] (rarely appropriate),
  • toArray(T[]) if you want to reuse an existing array (should be large enough),
  • toArray(IntFunction<T[]>) if you want type safety and a new array.
like image 193
Zabuzard Avatar answered Sep 23 '22 12:09

Zabuzard