Card 01/ 08

ConceptDifficulty: Intermediate1 min

Collection Interfaces: List, Set and Queue

More than twenty classes, three interfaces, and one promise each that decides which to use.

The Java Collections Framework is the standard library's set of classes for holding a group of objects. Its core is three interfaces, List, Set and Queue, and each makes one promise about what it does with what you put in it. Choosing a collection starts with choosing the promise.

The library ships more than twenty classes that hold a group of things. Choosing between them by reading twenty sets of documentation is not a plan, and it is what most people end up doing.

The three collection interfaces and the promise each one makes
InterfaceThe promiseTypical class
ListKeeps the order you added things in, and keeps duplicatesArrayList
SetHolds each distinct element once, and decides what distinct meansHashSet
QueueDecides which element comes out nextArrayDeque
java
List<String> ordered = new ArrayList<>();
Set<String> unique = new HashSet<>();
Queue<String> pending = new ArrayDeque<>();

All three extend Collection, which holds the methods they share: add, size, contains, and iterator, which returns an object that walks the elements one at a time. The promise is what they do not share, and it is the only thing worth choosing on.

So the first question about any group of things is which promise it needs: does the order matter, do duplicates matter, and does something decide what comes out next. Answer those three and the class list shrinks to one line, usually ArrayList, HashSet or ArrayDeque.