posted 19 years ago
If you have to write this against a Collection rather than List, you have no choice but to iterate (toArray will iterate and allocate an array, so it's possibly more expensive [ArrayList has an array already, so it can use System.arraycopy(), so it won't iterate, but I digress]).
The reason is that Collection is the lowest common denominator of a "thing that holds other objects," and it has no concept of ordering. List provides indexed access, allowing you to call list.get(0) and list.get(list.size()-1).
Note that this implies that Collection itself doesn't have any idea of "first" and "last" elements. In fact, it's conceivable (though unlikely in practice) that getting the first and last elements from a generic Collection could return different elements on subsequent calls.
For example, if I'm holding five coins in my hand, which one is the first one? And after I shake them around in my hand? The collection of coins hasn't changed since they are unordered.
Are you sure you don't have a List?