The Collections framework map
◈ 5 cardsCollection vs Map, the List / Set / Queue interfaces and their implementations, and programming to the interface.
Two root hierarchies
The Java Collections Framework splits into two unrelated roots:
Collection<E>— a group of individual elements. Its three sub-interfaces are:- -
List<E>— ordered, allows duplicates, index access. Impls:ArrayList,LinkedList. - -
Set<E>— no duplicates. Impls:HashSet(no order),LinkedHashSet(insertion order),TreeSet(sorted). - -
Queue<E>— ordering for processing (FIFO/priority). Impls:LinkedList,ArrayDeque,PriorityQueue. Map<K,V>— key→value associations.Mapis NOT aCollection— it has its own hierarchy. Impls:HashMap,LinkedHashMap,TreeMap.
Knowing this map lets you answer the exam's favourite question — "which collection would you use for X?" — by elimination: need key lookup → Map; need uniqueness → Set; need order/index/duplicates → List; need FIFO or priority processing → Queue.
### Program to the interface
Declare variables with the interface type and instantiate the concrete class only at new:
List<Event> events = new ArrayList<>(); // good: caller depends on List
This is exactly what the Greenhouse project's Controller does (private List<Event> eventList = new ArrayList<Event>();). The benefit: every method that takes or returns a List<Event> is decoupled from the implementation — you can swap ArrayList for LinkedList by changing one line, and no caller breaks. Declaring ArrayList<Event> events = ... instead would leak the implementation into every signature.
Worked example. A method that accepts any collection. Because it takes Collection<Event>, you can pass an ArrayList, a HashSet, a LinkedList, or anything else that implements Collection:
static int countReady(Collection<Event> events) {
int n = 0;
for (Event e : events) // for-each works on any Iterable
if (e.ready()) n++;
return n;
}
The <> on the right (the diamond operator) infers the type argument from the left-hand declaration, so you write new ArrayList<>() not new ArrayList<Event>().