1. University MCA (AI/ML) Semester 2
  2. CAP477
  3. Unit 4

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):

ClassBackingget(i)add/remove in middle
ArrayListresizable arrayO(1)O(n)
LinkedListdoubly linked listO(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

Question 1 · Tier 3, Apply

TreeSet<Integer> with 10, 20, 30, 40: what are floor(25) and ceiling(25)?

  1. null and null
  2. 20 and 30
  3. 25 and 25
  4. 30 and 20
Show the answer

B. floor is the greatest element <= 25 and ceiling the smallest >= 25: 20 and 30.

Question 2 · Tier 1, Recall

Which Set implementation keeps its elements sorted?

  1. LinkedHashSet
  2. HashSet
  3. TreeSet
  4. ArraySet
Show the answer

C. TreeSet of pear, apple, fig prints [apple, fig, pear].