I'm working on some Java code, using J2SDK 1.4. And I needed to turn a java.util.ArrayList of Foo objects into an array of Foo objects. So naturally I thought about java.util.Collection's
public Object[] toArray(Object[] a)
method. It's been a while since I last used this method. So I surfed over to the Javadoc at Sun's Java website. The first thing that jumped into my eyes is this code sample:
String[] x = (String[]) v.toArray(new String[0]);
That's exactly what I needed (and eventually what I did.) However something else caught my eyes too:
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.
What that means is that if my List contains exactly three Foos, then I can either do:
Foo[] foos = (Foo[]) list.toArray(new Foo[0]);
or
Foo[] foos = new Foo[3];
list.toArray(foos);
to achieve the same result. The first alternative also works when we don't know the size of the List. The second alternative works only if I already know the size of the List. And the second way offers any advantage over the first only if the foos array can be reused in multiple toArray() calls. But if I know the size of the collection, I can probably avoid the use of List altogether.
How do you use Collection.toArray(Object[] a)? (I would really like to be educated about real world code where the second alternative wins over the first.)