Collections & Generics
Pick the right data structure and use it correctly.
Choose the right one
- Ordered, duplicates, index access
List → ArrayList
- Unique items
Set → HashSet
- Key → value pairs
Map → HashMap
- First-in-first-out
Queue → ArrayDeque
- Sorted
TreeSet / TreeMap
- Insertion order kept
LinkedHashSet / LinkedHashMap
List
List<String> l = new ArrayList<>();
l.add("a"); l.get(0); l.remove("a");l.size(); l.contains("a");
Map
Map<String,Integer> m = new HashMap<>();
m.put("k", 1); m.get("k");m.getOrDefault("x", 0);for (var e : m.entrySet()) { e.getKey(); e.getValue(); }
Generics
class Box<T> { T value; }type parameter<T extends Number>
bounded type? extends T
producer (read out)? super T
consumer (write in)- PECS: Producer Extends, Consumer Super