This is something that has long irritated me, but I've never been able to find a solution. If I have a List of apples and I want to turn it into an array of apples, I have to do this:
I'd love to be able to do this:
Unfortunately, this doesn't work because the toArray method returns an array of Objects, not an array of Apples. So is there any better way to do this? Having to write that silly for loop any time I want to make this happen seems so wasteful.
Campbell Ritchie wrote:You may be able to use the no-arguments toArray method and cast the resultant array.
No you may not. toArray() returns an Object[] - both in reference type and in actual type. Casting this to anything else, like Apple[], will throw a ClassCastException.
This is a very good topic. You guys answered well because I equally had same experience some times back.
But, am yet really fish out what List<T>.toArray() does.
In what situation can it be used?
Maybe code sample will clearify that.
Help?
Collection.toArray() does something that looks like this (actual implementation usually is different but the results are the same):
Collection.toArray(T[]) on the other hand does something like this (again, actual implementation may vary):
The most important step there is line 5 - instead of creating a new Object[] it uses reflection to create an array of the proper type.
Thanks for the replies, folks. I had seen that method there, but I guess I never paid any attention to what it did. As an addendum to Rob's reply, here's the actual implementation of the method ArrayList.toArray(T[] t):