stanleyerror
stanleyerror

Reputation: 788

Confused about `toArray(T[] a)` method in java

The List has a method toArray such as:

<T> T[] java.util.ArrayList.toArray(T[] a)

When calling this method, I should create a new instance and pass it toArray(new MyElementClass[0]).

Could it be defined like this:

<T> T[] java.util.ArrayList.toArray(Class<T>)

By calling toArray(MyElementClass[].class), can it be more effective?

Upvotes: 1

Views: 112

Answers (2)

newacct
newacct

Reputation: 122439

The way toArray is now, it allows you to re-use an array (it will use the given array if it is of sufficient size) rather than always needing to allocate a new one.

Upvotes: 1

k_g
k_g

Reputation: 4464

It would be. However, the original method is given for backwards compatibility.

See this

Upvotes: 3

Related Questions