Card 01/ 08

ConceptDifficulty: Intermediate1 min

Three Interfaces, and the One Promise Each Makes

The standard 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 map is much smaller than the class list. There are three interfaces, and each makes one promise about what it will do with what you put in it.

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 is where the methods they share live — add, size, contains, iterator. 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 not which class but which promise: does the order matter, do duplicates matter, and does something decide what comes out next. Answer those three and the class list has collapsed to one line.