CAP477 · Unit 4: Collections and functional Java
List and Set collections
9 practice questions
Key points
- ArrayList fast get, LinkedList cheap inserts
- HashSet unordered, LinkedHashSet insertion order, TreeSet sorted
- Override hashCode whenever you override equals
- Remove with Iterator or removeIf, not inside for-each
The Collections Framework (java.util) gives ready-made data structures behind interfaces: Collection -> List, Set, Queue/Deque; Map is separate.
List (ordered, duplicates allowed, index access):
| Class | Backing | get(i) | add/remove in middle |
|---|---|---|---|
| ArrayList | resizable array | O(1) | O(n) |
| LinkedList | doubly linked list | O(n) | O(1) once positioned |
add(x), add(i, x), set(i, x), remove(int index), remove(Object), indexOf, contains, subList (a view of the original), removeIf. For [5, 1, 5] then add(0, 9), set(1, 7) the list is [9, 7, 1, 5]. Collections.sort, reverse, max, frequency. Arrays.asList(...) is fixed-size (set works, add throws UnsupportedOperationException); List.of(...) is immutable.
Removing while iterating: removing inside a for-each loop throws ConcurrentModificationException; use Iterator.remove() or removeIf.
Set (no duplicates):
HashSet: hash table, O(1), no order guaranteed.LinkedHashSet: keeps insertion order ([z, a, m]).TreeSet: sorted (red-black tree), O(log n);first,last,floor,ceiling,lower,higher,headSet,tailSet.
Set algebra: addAll (union), retainAll (intersection), removeAll (difference).
equals/hashCode contract: equal objects must have equal hash codes. A class that overrides equals but not hashCode is treated as distinct by HashSet/HashMap (size 2 instead of 1 in the demo).
Queues: ArrayDeque (stack with push/pop, queue with addLast/pollFirst), LinkedList as a queue, PriorityQueue (min-heap by default; Collections.reverseOrder() for max).
Exam pitfall: remove(1) on List<Integer> removes an index, not the value.
Try two questions
TreeSet<Integer> with 10, 20, 30, 40: what are floor(25) and ceiling(25)?
- null and null
- 20 and 30
- 25 and 25
- 30 and 20
Show the answer
B. floor is the greatest element <= 25 and ceiling the smallest >= 25: 20 and 30.
Which Set implementation keeps its elements sorted?
- LinkedHashSet
- HashSet
- TreeSet
- ArraySet
Show the answer
C. TreeSet of pear, apple, fig prints [apple, fig, pear].