Card 01/ 08
All 8 cards
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.
| Interface | The promise | Typical class |
|---|---|---|
List | Keeps the order you added things in, and keeps duplicates | ArrayList |
Set | Holds each distinct element once, and decides what distinct means | HashSet |
Queue | Decides which element comes out next | ArrayDeque |
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.