Skip to content
AgileLogics
6 min read

The Collections Framework

Prerequisites: Generics

Beyond ArrayList, the Collections Framework offers several interfaces suited to different needs:

import java.util.*;

List<String> list = new ArrayList<>();   // ordered, duplicates allowed
Set<String> set = new HashSet<>();       // unique elements, no order guarantee
Set<String> ordered = new LinkedHashSet<>(); // unique, insertion order kept
Map<String, Integer> map = new HashMap<>();  // key -> value pairs

map.put("Ada", 36);
map.put("Grace", 85);
System.out.println(map.get("Ada"));         // 36
System.out.println(map.containsKey("Bob")); // false

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " is " + entry.getValue());
}

Choosing between them: List when order and duplicates matter, Set when you only care whether something is present, Map when you need to look values up by a key.

Common mistakes

  • Modifying a list while iterating it with a for-each loop — throws ConcurrentModificationException. Use an Iterator's own .remove(), or collect items to remove into a separate list first.