Memra

Framework overview: Collection vs Map

◈ 3 cards

The core interfaces — List, Set, Queue/Deque, Map — and how Iterable fits in.

Two hierarchies, not one

The Java Collections Framework is split into two parallel hierarchies:

  • Collection<E> — for groups of individual elements. Sub-interfaces: List, Set, Queue, Deque.
  • Map<K,V> — for key→value mappings. Not a Collection.
Iterable<T>
  └── Collection<E>
        ├── List<E>       — ordered, indexed, duplicates allowed
        ├── Set<E>        — no duplicates
        └── Queue<E>      — FIFO/priority access
              └── Deque<E> — double-ended queue (stack or queue)

Map<K,V>                  — keys unique, values may repeat
  ├── HashMap
  ├── LinkedHashMap
  └── SortedMap → TreeMap

Iterable<T> sits above Collection in the hierarchy. Any class that implements Iterable can be used in a for-each loop. It has one method: Iterator<T> iterator(). Iterator itself exposes hasNext() and next().

The most important concrete classes paired with their interfaces:

InterfaceCommon implementations
ListArrayList, LinkedList
SetHashSet, LinkedHashSet, TreeSet
Queue/DequeArrayDeque, LinkedList
MapHashMap, LinkedHashMap, TreeMap

Programming to the interface (List<String> list = new ArrayList<>()) is the recommended idiom: it lets you swap implementations without changing any other code.

Iterable<T>iterator()Collection<E>List<E>indexed, duplicatesSet<E>no duplicatesQueue<E>FIFO / priorityDeque<E>both ends
Everything on this tree inherits iterator(), which is what makes it usable in a for-each loop. Note what is absent: Map is nowhere on it.
Map<K,V>not a CollectionHashMapno orderLinkedHashMapinsertion orderSortedMapTreeMapsorted keys
Map is a second, unconnected hierarchy — it is not a Collection and has no iterator() of its own. You iterate one of its three views instead: keySet(), values() or entrySet().
NORMAL ~/memra/learn/java-from-zero/collections-framework-overview utf-8 LF