Lecture 16: Case Study: The JavaCollections APIYou can’t be a competent Java programmer without understanding the crucial parts ofthe Java library. The basic types are all in java.lang, and are part of the language prop-er. The package java.utilprovides collections – sets, lists and maps – and you shouldknow it well. The package java.iois also important, but you can get away with only arough familiarity with what’s in it, delving in as needed.In this lecture, we’ll look at the design of java.util, often called the Java ‘collections API’.It’s worth understanding not only because the collection classes are extremely useful,but also because the API is a nice example of well-engineered code. It’s fairly easy tounderstand, and is very well documented. It was designed and written by Joshua Bloch,who wrote the Effective Javabook that we recommended at the start of term.At the same time, though, almost all the complexities of object-oriented programmingappear somewhere in it, so if you study the API carefully, you’ll get a broad under-standing of programming issues that you probably haven’t yet considered in your owncode. In fact, it wouldn’t be an exaggeration to say that if you figure out how just oneof the classes (eg, ArrayList) works in its entirety, then you will have mastered all theconcepts of Java. We won’t have time to look at all the issues today, but we’ll touch onmany of them. Some of them, such as serialization and synchronization, are beyond thescope of the course.16.1Type HierarchyRoughly, the API offers three kinds of collection: sets, lists and maps. A set is a collec-tion of elements that does not maintain their order or their count – each element iseither in the set or not. A list is a sequence of elements, and thus maintains both orderand count. A map is an association between keys and values: it holds a set of keys, andmaps each key to a single value.The API organizes its classes with a hierarchy of interfaces – the specifications of thevarious types – and a separate hierarchy of implemention classes. The diagram showssome select classes and interfaces to illustrate this. The interface Collectioncapturesthe common properties of lists and sets, but not maps, but we’ll use the informal term93
‘collections’ to refer to maps anyway. SortedMapand SortedSetare used for maps andsets which provide additional operations to retrieve the elements in some order.The concrete implementation classes, such as LinkedList, are built on top of skeletalimplementations, such as AbstractList, from which they inherit. This parallel structureof interfaces and classes is an important idiom that is worth studying. Many novice94extendsAbstractCollectionCollectionSetListSortedSetextendsAbstractSetAbstractListimplementsimplementsimplementsimplementsHashSetTreeSetextendsAbstractSequentialListLinkedListinterfacesArrayListextendsextendsextends
programmers are tempted to use abstract classes when they should be using interfaces.