Java Collection Framework Hierarchy
The Java Collection Framework (JCF) is a unified architecture of interfaces, implementations (classes), and algorithms to store and process groups of objects. This guide explains the full hierarchy: Collection (List/Set/Queue/Deque), Map, their sorted/navigable variants, core implementations, iterators, and key concurrent & legacy types.
Block Diagram (Hierarchy Overview)
Iterable
│
(iterator())
│
Collection
┌───────────────────┼───────────────────┐
│ │ │
List Set Queue
│ │ │
┌─────┼─────┐ ┌──────┼──────┐ ┌──┴────────┐
ArrayList LinkedList HashSet LinkedHashSet PriorityQueue Deque
Vector │ │ │ │
│ also SortedSet (insertion ArrayDeque
Stack Deque │ order) LinkedList
(legacy) NavigableSet (Deque)
│
TreeSet
Map (not a child of Collection)
┌─────────────┼────────────────┬───────────────┐
HashMap LinkedHashMap WeakHashMap IdentityHashMap
│
SortedMap
│
NavigableMap
│
TreeMap
Iterators: Iterator, ListIterator (for List), Spliterator (parallel)
Core Roots
Iterable
- Root for all collection types (except
Mapbranch). - Provides
iterator()for enhancedfor-loop traversal; defaultforEach().
Collection
- Defines common ops:
add,remove,contains,size,isEmpty,iterator, etc. - Subinterfaces: List, Set, Queue, Deque.
List — Ordered, Indexed, Allows Duplicates
- ArrayList: resizable array; O(1) average random access; mid-inserts/removals costlier.
- LinkedList: doubly-linked; O(1) add/remove at ends; O(n) indexed access; also implements Deque.
- Vector (legacy): synchronized ArrayList; generally avoid; replaced by collections + external sync.
- Stack (legacy): extends Vector; LIFO (
push,pop); prefer ArrayDeque for stacks.
Set — No Duplicates
- HashSet: backed by HashMap; no order guarantees; O(1) average ops.
- LinkedHashSet: maintains insertion order; slight overhead vs HashSet.
- SortedSet: keeps elements in ascending order (by natural/comparator).
- NavigableSet: extends SortedSet with navigation (
lower,floor,ceiling,higher,pollFirst,pollLast). - TreeSet: Red–Black tree; implements NavigableSet (sorted + navigation).
- EnumSet: high-performance set for enums; memory-efficient bit vectors.
Queue — Typically FIFO
- Queue: methods like
offer/add,poll/remove,peek/element. - PriorityQueue: priority ordering (natural or comparator); head = smallest/highest-priority element.
Deque — Double-Ended Queue
- Deque (pronounced “deck”): supports adds/removes at both ends (
addFirst,addLast,pollFirst, etc.). - ArrayDeque: resizable circular buffer; excellent stack/queue; no capacity restrictions by default.
- LinkedList: also a Deque; good for frequent head/tail operations.
Map — Key–Value Pairs (Keys Unique)
- Map: core ops
put,get,containsKey,entrySet,keySet,values. - HashMap: unordered; allows one
nullkey + manynullvalues; O(1) average ops. - LinkedHashMap: maintains insertion order (or access-order if enabled) — great for LRU caches.
- SortedMap: keys kept in ascending order.
- NavigableMap: extends SortedMap with navigation (
lowerEntry,floorKey,ceilingEntry, etc.). - TreeMap: Red–Black tree; implements NavigableMap (sorted + navigation).
- WeakHashMap: weakly-referenced keys; entries can vanish when keys are GC-eligible — useful for caches.
- IdentityHashMap: uses reference equality (
==) for keys, notequals(). - Hashtable (legacy): synchronized map; generally superseded by ConcurrentHashMap/Collections.synchronizedMap.
- Properties (legacy): Hashtable subclass for string key/value configs; supports loading/storing from streams.
Iterators & Spliterators
- Iterator:
hasNext,next,remove. - ListIterator: bidirectional list iterator; supports
add,set, index retrieval. - Enumeration (legacy): older cursor for Vector/Hashtable; replaced by Iterator.
- Spliterator: supports parallelism characteristics (size, ordered, sorted, distinct, concurrent); used by streams.
Concurrent Collections (java.util.concurrent)
Thread-safe, high-throughput structures for concurrent programs:
- ConcurrentHashMap: scalable map with lock striping & non-blocking reads.
- CopyOnWriteArrayList/CopyOnWriteArraySet: snapshot-style iterators; great for read-mostly workloads.
- ConcurrentLinkedQueue, ConcurrentLinkedDeque: lock-free, high-throughput queues/deques.
- BlockingQueue family: ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue, DelayQueue.
- ConcurrentSkipListMap/ConcurrentSkipListSet: concurrent, Navigable, sorted structures (skip-lists).
Choosing the Right Type (Quick Tips)
- Random access: ArrayList
- Frequent head/tail ops: ArrayDeque (stack/queue), LinkedList (deque)
- Unique, unordered items: HashSet (or LinkedHashSet to preserve insertion order)
- Sorted + range queries: TreeSet / TreeMap (Navigable*)
- LRU/access-order map: LinkedHashMap with accessOrder=true
- Thread-safe & scalable: ConcurrentHashMap, ConcurrentLinkedQueue, BlockingQueue
- Enum keys/values: EnumSet / EnumMap
Mini Examples
// Sorted/Navigable examples java.util.NavigableSetns = new java.util.TreeSet<>(); ns.addAll(java.util.Arrays.asList(10,20,30)); System.out.println(ns.ceiling(25)); // 30 System.out.println(ns.floor(20)); // 20 java.util.NavigableMap nm = new java.util.TreeMap<>(); nm.put("apple",3); nm.put("banana",2); nm.put("cherry",1); System.out.println(nm.lowerKey("banana")); // apple System.out.println(nm.ceilingEntry("b")); // banana=2 // Deque as stack/queue java.util.Deque dq = new java.util.ArrayDeque<>(); dq.addFirst(1); dq.addLast(2); dq.push(3); // stack push System.out.println(dq.pollFirst()); // 3 (LIFO if using push/pop) System.out.println(dq.pollLast()); // 2 // LinkedHashMap LRU-style (access order) java.util.Map lru = new java.util.LinkedHashMap<>(16,0.75f,true); lru.put(1,"A"); lru.put(2,"B"); lru.get(1); lru.put(3,"C"); System.out.println(lru.keySet()); // [2, 1, 3] — access order
Legacy Summary
- Vector, Stack, Hashtable, Enumeration, Properties — retained for backward compatibility; prefer modern counterparts.
Conclusion
Mastering the Collection Framework means understanding interfaces (behaviors) and the implementations (performance & ordering). Choose by access pattern (random vs sequential), ordering (none/insertion/sorted), uniqueness (Set), and threading needs (concurrent vs single-threaded). When in doubt, start with ArrayList, HashMap, and HashSet, then refine based on ordering, duplication, or concurrency requirements.
Comments
Post a Comment