1

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?

4
  • Probably yes, although you could always keep a number of constants with zero-length arrays of each of the types that you need. But the question is very hypothetical, since you can't change the API classes. Commented Jan 11, 2015 at 6:37
  • It would have to be Class<T> rather than Class<?>. Commented Jan 11, 2015 at 6:42
  • List is interface and it does not have method called "toArray". There is implementation of this interface called ArrayList which does. Just to not confuse other people Commented Jan 11, 2015 at 7:04
  • If it was <T> T[] toArray(Class<T>), then you would have to call it as toArray(MyElementClass.class) Commented Jan 12, 2015 at 0:53

2 Answers 2

3

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

See this

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.