Java Essentials: The Collections Framework
Why Collections?
Arrays are fine when the size is fixed, but most programs need structures that grow and shrink. The Java Collections Framework supplies reusable containers built on a few core interfaces. The three you will use most are List, Set, and Map.
- List - an ordered collection that allows duplicates.
- Set - a collection that forbids duplicates and has no meaningful order.
- Map - a collection of key to value pairs, like a phone directory.
Choosing Implementations
ArrayList stores elements in a resizable array, which makes random access fast. LinkedList chains nodes, which suits some insert and remove workloads. HashSet uses hash codes for near-instant lookups. HashMap is the standard map and allows one null key and many null values.
List<String> names = new ArrayList<>();
names.add("Ava");
names.add("Liam");
for (String name : names) {
System.out.println(name);
}The diamond operator <> lets the compiler infer the type argument, so you do not repeat it. The enhanced for loop reads every element of the list without managing an index.
Maps by Example
Map<String, Integer> scores = new HashMap<>();
scores.put("Ava", 95);
scores.put("Liam", 88);
int avaScore = scores.get("Ava");
System.out.println(avaScore);A map is great when you want to look up a value quickly by a natural key, such as a username, an email, or an id. Iterating a map usually means walking its key set or its entries.
Sorting and Searching
Because everything implements a common interface, Collections.sort and Collections.binarySearch work across many container types. Custom object ordering uses Comparable or a Comparator passed to the sort method.
Key Points
- List, Set, and Map are the three core collection interfaces.
- ArrayList, HashSet, and HashMap cover the most common needs.
- Iterate with the enhanced for loop over collections and maps.
- Common utilities like sorting live in the Collections class.