leifg leifg - 10 months ago 34
Java Question

Why no tail() or head() method in List to get last or first element?

I recently had a discussion with a collegue why the List interface in Java doesn't have a


In order to implement such a functionality would have to write a wrapper that looked something like this:

public E head() {
if (underlyingList == null || underlyingList.isEmpty())
return null;

return underlyingList.get(0);

public E tail() {
if (underlyingList == null || underlyingList.isEmpty())
return null;

return underlyingList.get(underlyingList.size()-1);

I'm not aware of all List implementations but I assume that at least in LinkedList and ArrayList it should be pretty trivial to get the last and first element (constant time).

So the question is:

Is there a specific reason why it is not a good idea to provide a tail method to any List implementation?


Java Collections Framework is written by Joshua Bloch. One of his API design principles is: High power-to-weight ratio.

tail() and head() can be implemented by get() and size(), so it's not necessary to add tail() and head() to a very general interface java.util.List. Once users use the methods, you don't have chance to remove them and you have to maintain these unnecessary methods forever. That's bad.