Reading — step 1 of 5
Learn
~1 min readGenerics and Collections
The four core interfaces in java.util:
List<T>— ordered, allows duplicates.ArrayList,LinkedList.Set<T>— unique elements, no order guarantee.HashSet,LinkedHashSet,TreeSet.Map<K, V>— key-value.HashMap,LinkedHashMap,TreeMap.Queue<T>/Deque<T>—ArrayDeque,LinkedList,PriorityQueue.
List<String> list = new ArrayList<>();
list.add("a"); list.add("b");
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3, 1)); // {1,2,3}
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);
ages.getOrDefault("Carol", -1); // -1
for (Map.Entry<String, Integer> e : ages.entrySet()) {
System.out.println(e.getKey() + ": " + e.getValue());
}
Variants worth knowing:
LinkedHashMap— preserves insertion orderTreeMap— sorted by keyConcurrentHashMap— thread-safe
Immutable factories (Java 9+): List.of(1, 2, 3), Map.of("a", 1, "b", 2). Cannot be modified — add() throws.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…