I’m trying to understand the API inconsistency in the Java standard collections library.
There is no method in List or in AbstractList to get the last item, although one can simulate that with size and getIndex().
However, LinkedList supports that function.
Any idea why it was decided not to support this method in the interface?
The
java.util.Listinterface doesn’t supportgetLast()because the designers went for a ‘minimal interface’. With the minimal number of methods defined it makes it both easier to understand and quicker to learn.This is in contrast with a ‘humane interface’ (such as used in the Ruby array class) which attempts to provide methods for doing common operations (e.g.
getLast()). As there are many uses which such a fundamental concept as a list can be put to this tends to lead to much larger interfaces.For further information see Martin Fowler’s Minimal Interface and Humane Interface descriptions.
As to why LinkedList supports
getLast()etc., to quote the javadoc:Presumably it was felt that a general List would not be adequate for these specific use cases.
As an insight into the mind of the principal designer of the Java Collections API (Joshua Bloch) he provides this list of API design maxims by which he works. Of which, the most pertinent to this question are:
However he also states:
Which just shows that design guidelines often conflict and the hardest part of an API designers job is to balance these conflicts.