Collection.toArray(T) will return the array you passed to it if it is large enough. In short, the following is done (pseudo code):
By actually passing in an array that already has length size() you make sure the array itself is large enough, so it will be returned.
If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.
Rob Prime wrote:Hate to burst your bubble, but it is.
I believe Campbell was referring to the code shown in the link:
And I agree, it's inelegant to assign twice; it's unnecessary, and suggests a misunderstanding of how toArray() works. The code John found later is nicer. Alternately, this also eliminates the double assignment:
And in fact, the presence of these multiple, seemingly contradictory paradigms suggests to me that the original API design of toArray() is less clear than it might have been. It's a pity that Java generics were implemented as they are; a non-erasable implementation might have allowed us to do something nice and simple like
Yes, because zero-length arrays with no reference retained are soooo wasteful. Your threshold for "horrible" seems quite a bit lower than mine. Whatever.
More importantly: I wasn't actually endorsing that code; I was just pointing out that there were multiple usage patterns, leading to user confusion on how to use that method. Which is, IMO, bad. But I would also note that of all the possible usage patterns, that's the one that is actually endorsed, specifically, by )]the official API. And yet it's not, in my opinion, very elegant. So I'm kind of at a loss, trying to figure out what it is you actually have an issue with. In my opinion, the API is poorly designed. It's possible to use it elegantly, but also inelegantly, and the latter is extremely common. That's not my fault, nor Campbell's fault - it's Sun's. So why are you busting our chops instead?
I guess it's just a matter of differences in style. I like to avoid creating objects you throw away immediately. I usually go for the "toArray(new Integer[c.size()])" solution, but when that would make the line too long I will use a temp variable to increase readability.
Let's drop this, shall we? In the end the code examples both you and John provided all work like a charm, so it's up to the programmer to decide which one he/she prefers.
What about the no-args toArray() method and cast it to String? No you can't; I tried and got a ClassCastException.I ran it several times. Oddly enough most of the time it appears significantly faster to pass a zero-length array to the toArray method.