Core Module
12 min forge
Java Collections Overview
The hierarchy of the Collections Framework and why it's used.
Java Collections Overview
π What is it
The Java Collections Framework (JCF) is a set of classes and interfaces that implement commonly used collection data structures. It provides a standardized way to handle groups of objects.
ποΈ Hierarchy
- Collection (Interface): The root of the hierarchy.
- List: Ordered collection (ArrayList, LinkedList, Vector).
- Set: Unordered collection, no duplicates (HashSet, LinkedHashSet, TreeSet).
- Queue: FIFO structure (PriorityQueue, Deque).
- Map (Interface): Key-Value pairs, not a subtype of Collection (HashMap, TreeMap, LinkedHashMap).
β‘ When to use
Use the Collections Framework whenever you need to store, retrieve, manipulate, and communicate aggregate data.
π§ Big-O Summary
| Collection | Add | Get | Remove |
|---|---|---|---|
| ArrayList | $O(1)$* | $O(1)$ | $O(n)$ |
| LinkedList | $O(1)$ | $O(n)$ | $O(1)$ |
| HashSet | $O(1)$ | $O(1)$ | $O(1)$ |
| HashMap | $O(1)$ | $O(1)$ | $O(1)$ |
| TreeSet | $O(\log n)$ | $O(\log n)$ | $O(\log n)$ |
| *Amortized |
β Common mistakes
- Using Vector: Using the legacy
Vectorclass (it's synchronized and slow; useArrayListunless you need thread-safety). - Modification during iteration: Trying to remove items from a collection while iterating over it using a simple
for-eachloop (throwsConcurrentModificationException). - Ignoring Generics: Not using generics (e.g.,
List<String>), leading to runtime type errors.