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?

stanleyerror
  • 650
  • 1
  • 8
  • 22
  • 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. – Erwin Bolwidt Jan 11 '15 at 06:37
  • It would have to be `Class` rather than `Class>`. – user253751 Jan 11 '15 at 06: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 – rkosegi Jan 11 '15 at 07:04
  • If it was ` T[] toArray(Class)`, then you would have to call it as `toArray(MyElementClass.class)` – newacct Jan 12 '15 at 00:53

2 Answers2

3

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

See this

Community
  • 1
  • 1
k_g
  • 4,019
  • 2
  • 20
  • 37
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.

newacct
  • 110,405
  • 27
  • 152
  • 217