List, Set, Queue and Map with their common implementations
| Class | Order | Duplicates | Lookup |
|---|---|---|---|
| ArrayList | Insertion | Yes | get(i) O(1) |
| LinkedList | Insertion | Yes | get(i) O(n) |
| HashSet | None | No | O(1) |
| TreeSet | Sorted | No | O(log n) |
| HashMap | None | Keys unique | O(1) |
| TreeMap | Sorted by key | Keys unique | O(log n) |
List<Integer> list = new ArrayList<>(List.of(5, 2, 8));
Collections.sort(list); // [2, 5, 8]
Map<String, Integer> freq = new HashMap<>();
for (String w : "a b a c a".split(" "))
freq.put(w, freq.getOrDefault(w, 0) + 1);
System.out.println(freq); // {a=3, b=1, c=1}
Set<String> set = new TreeSet<>(List.of("b", "a", "b")); // [a, b]
Q & A
-
HashMap vs Hashtable?HashMap is not synchronized, allows one null key, faster. Hashtable is synchronized (legacy) and allows no null. For threads use ConcurrentHashMap.
-
How does HashMap work?hashCode() picks a bucket; entries in the same bucket form a linked list (a red-black tree after 8 entries); equals() finds the exact key.