Understanding Java Collection Framework: Interfaces, Implementations, and Usage
This article provides a comprehensive overview of Java's collection framework, covering the core Collection interface, List, Set, and Map interfaces, their common implementations such as ArrayList, LinkedList, Vector, Stack, Hashtable, and HashMap, and demonstrates traversal using the Iterator pattern with code examples.
Interface: Collection
The Collection interface is the most basic collection interface, representing a group of Objects. Some collections allow duplicate elements, others do not; some support ordering, others do not. Java SDK does not provide a direct class that implements Collection; instead it offers sub‑interfaces such as List and Set.
All classes that implement Collection must provide two standard constructors: a no‑argument constructor that creates an empty collection, and a constructor that accepts another Collection to copy its elements.
The key method boolean add(Object o) returns true if the collection's contents changed after the call, not merely whether the addition succeeded. Similar semantics apply to addAll, remove, removeAll, and retainAll.
Using the Iterator Pattern to Traverse Collections
Collection provides the iterator() method, which returns an Iterator for traversing all elements. The Iterator pattern abstracts the traversal logic away from concrete collection classes, preventing clients from seeing internal structures. Typical usage:
Iterator it = collection.iterator();
while (it.hasNext()) {
Object obj = it.next(); // obtain next element
}The Iterator maintains internal state, so client code does not need to manage traversal pointers. Different collections may return different concrete Iterator types, but all implement the Iterator interface.
To ensure reliable traversal, avoid modifying the collection during iteration (except via the Iterator's remove() method). Use a single thread or synchronize traversal in multithreaded contexts.
List Interface
List is an ordered Collection that allows precise control over element insertion positions using an index, similar to array indexing. Unlike Set, List permits duplicate elements.
In addition to iterator(), List provides listIterator(), which returns a ListIterator with additional methods such as add(), remove(), and set(), enabling bidirectional traversal.
Common implementations of List include LinkedList, ArrayList, Vector, and Stack.
LinkedList Class
LinkedList implements List, permits null elements, and offers extra methods for adding, removing, or inserting at the head or tail, making it suitable for use as a stack, queue, or deque.
LinkedList is not synchronized; if multiple threads access it concurrently, external synchronization is required, e.g.,
List list = Collections.synchronizedList(new LinkedList(...));ArrayList Class
ArrayList implements a dynamically resizable array. It allows all elements, including null, and is unsynchronized. Methods size, isEmpty, get, and set run in constant time, while add has amortized constant time; adding n elements costs O(n).
Each ArrayList has a capacity that grows automatically as elements are added, though the growth algorithm is not specified. For large insertions, calling ensureCapacity can improve performance.
Vector Class
Vector is similar to ArrayList but is synchronized. Its iterators are also synchronized; if one thread modifies the Vector while another is iterating, a ConcurrentModificationException may be thrown, requiring appropriate exception handling.
Stack Class
Stack extends Vector to provide a last‑in‑first‑out (LIFO) stack. It adds five methods— push, pop, peek, empty, and search —to support typical stack operations.
Set Interface
Set is a Collection that does not contain duplicate elements; at most one null element is allowed. The constructor that accepts a Collection must ensure the incoming collection contains no duplicates.
Care must be taken when mutable objects are stored in a Set; if a mutable element changes such that its equals result changes, the Set's behavior can become inconsistent.
Map Interface
Map does not extend Collection; it provides a key‑to‑value mapping where keys must be unique. Map offers three collection views: a set of keys, a collection of values, and a set of key‑value entries.
Hashtable Class
Hashtable implements Map with synchronized methods. Any non‑null object can be used as a key or value. Basic operations put(key, value) and get(key) run in constant time.
Performance can be tuned via initial capacity and load factor (default 0.75). Example usage:
Hashtable numbers = new Hashtable();
numbers.put("one", new Integer(1));
numbers.put("two", new Integer(2));
numbers.put("three", new Integer(3));
Integer n = (Integer)numbers.get("two");
System.out.println("two = " + n);Keys must correctly implement hashCode and equals. If two equal objects have different hash codes, or unequal objects share the same hash code, hash collisions can degrade performance or cause unexpected results. Always override both methods together.
HashMap Class
HashMap is similar to Hashtable but is unsynchronized and permits null keys and values. When viewed as a Collection via values(), iterator performance scales with the map's capacity, so avoid setting an excessively high initial capacity if iteration speed is critical.
WeakHashMap Class
WeakHashMap is a variant of HashMap that holds keys with weak references; if a key is no longer referenced elsewhere, it becomes eligible for garbage collection.
Summary
If you need stack or queue behavior, consider using a List implementation; use LinkedList for fast insertions/removals and ArrayList for fast random access.
In single‑threaded contexts, prefer unsynchronized classes for better performance; use synchronized classes when multiple threads may access the collection concurrently.
When working with hash‑based collections, always correctly override both equals and hashCode for key objects.
Prefer returning interface types (e.g., List) rather than concrete implementations (e.g., ArrayList) to keep client code flexible.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
