Sequenced Collections practice questions

From OCP Java SE 21 (1Z0-830) · 17 questions on this topic

Sequenced Collections practice questions from OCP Java SE 21 (1Z0-830). This pack has 17 questions tagged Sequenced Collections, drawn from its timed mock exams. 8 of them are worked through in full below — the question, every option, why each is right or wrong, and the explanation.

Worked examples for Sequenced Collections

  1. Question 1

    What does this print? ```java import java.util.*; public class Main { public static void main(String[] args) { LinkedHashMap<String, Integer> m = new LinkedHashMap<>(); m.put("a", 1); m.put("b", 2); m.put("c", 3); System.out.println(m.reversed()); } } ```

    1. A. {c=3, b=2, a=1}Correct answer

      LinkedHashMap implements SequencedMap in Java 21, and reversed() returns a view in the opposite encounter order; insertion order a, b, c reverses to c, b, a.

    2. B. {a=1, b=2, c=3}

      The original order: assumes reversed() mutates the receiver, or that map order is not something you can flip. reversed() returns a reversed view directly.

    3. C. {3=c, 2=b, 1=a}

      Reads reversed as inverted, swapping keys with values. reversed() never touches the entries themselves, only the order they are visited in.

    4. D. Compilation fails: reversed() is not declared on Map

      The right rule applied to the wrong static type. Map has no reversed(), but the variable is declared LinkedHashMap, which implements SequencedMap, so the method resolves.

    Explanation

    Trace: `LinkedHashMap` implements `SequencedMap` in Java 21, and `SequencedMap.reversed()` returns a view of the same entries in the opposite encounter order. The insertion order is `a`, `b`, `c`, so the reversed view iterates `c`, `b`, `a` and `AbstractMap.toString` renders it as `{c=3, b=2, a=1}`. Why the others are wrong: `{a=1, b=2, c=3}` is the original order — it assumes `reversed()` mutates the receiver and returns something you then have to re-read, or that map order is not a real thing you can flip. `{3=c, 2=b, 1=a}` reads "reversed" as *inverted*: keys swapped with values. `reversed()` never touches the entries themselves, only the order they are visited in. `Compilation fails: reversed() is not declared on Map` is the right rule applied to the wrong static type. `Map` genuinely has no `reversed()` — but the variable here is declared `LinkedHashMap`, which implements `SequencedMap`, so the method resolves. Exam tip: the sequenced methods hang off `SequencedMap`, not `Map`. Widen the same object to `Map<String, Integer> m` and this very line stops compiling — the exam loves changing only the declared type and asking again. `HashMap` is not sequenced at all, at any static type.

  2. Question 2

    Which two statements about the sequenced-collection hierarchy in Java 21 are correct? (Choose two.)

    1. A. Every List is a SequencedCollectionCorrect answer

      JEP 431 retrofits List to extend SequencedCollection, since a list has a well-defined encounter order with two ends.

    2. B. HashSet implements SequencedSet

      HashSet has no defined encounter order, so it stays a plain Set; LinkedHashSet is the sequenced one.

    3. C. Deque implements SequencedCollectionCorrect answer

      Deque also extends SequencedCollection under JEP 431, as it has a well-defined encounter order with a first and last end.

    4. D. SortedMap cannot be a SequencedMap

      SortedMap actually extends SequencedMap: sorted order is a valid encounter order, so a TreeMap has firstEntry()/lastEntry() too.

    Explanation

    JEP 431 retrofits existing types that already have a well-defined encounter order with two ends: List and Deque become SequencedCollections, LinkedHashSet and SortedSet become SequencedSets, and LinkedHashMap and SortedMap become SequencedMaps. Sorted types qualify because their comparator order is itself an encounter order. Only the hash-based types (HashSet, HashMap), which have no defined order, remain unsequenced.

  3. Question 3

    What is the output? ```java import java.util.*; public class Main { public static void main(String[] args) { List<Integer> l = new ArrayList<>(List.of(1, 2, 3)); System.out.println(l.reversed()); } } ```

    1. A. [1, 2, 3]

      This is the original insertion order; the code prints the reversed view, not the backing list, which is left untouched.

    2. B. [3, 2, 1]Correct answer

      reversed() returns a reverse-ordered view of the list; printing that view shows [3, 2, 1] while the original list keeps its order.

    3. C. Compilation fails: no reversed() on List

      Assumes List has no reversed(), but reversed() is a real List method in Java 21 via SequencedCollection, so the code compiles.

    4. D. Throws UnsupportedOperationException

      Creating or printing a view mutates nothing, so there is no unsupported operation to throw on.

    Explanation

    `reversed()`, added to List through SequencedCollection in Java 21, returns a reverse-ordered view of the list rather than mutating or copying it. Printing the view displays the elements in reverse while the backing list keeps its original order. Because it is a live view, any later mutation of the original list would also be visible through it.

  4. Question 4

    What does this print? ```java import java.util.*; public class Main { public static void main(String[] args) { LinkedHashMap<String, Integer> m = new LinkedHashMap<>(); m.put("b", 2); m.put("c", 3); m.putFirst("a", 1); System.out.print(m.firstEntry().getKey() + " " + m.lastEntry().getKey()); } } ```

    1. A. b c

      Ignores putFirst repositioning a to the front; a becomes the new first entry ahead of b.

    2. B. a b

      Forgets that c stays last; putFirst prepends a without displacing the existing tail entry c.

    3. C. Compilation fails: putFirst is not a member of LinkedHashMap

      LinkedHashMap implements SequencedMap in Java 21, so putFirst is a real member and the code compiles.

    4. D. a cCorrect answer

      After the two puts the encounter order is b, c; putFirst("a", 1) inserts a at the front, giving a, b, c, so firstEntry() is a and lastEntry() is c.

    Explanation

    LinkedHashMap implements SequencedMap in Java 21, so putFirst inserts a new mapping at the front of the encounter order without disturbing the existing entries at the tail. firstEntry() then reports the newly prepended key and lastEntry() the original final key. Note that putFirst/putLast also move an existing key to that end (remapping its value) if it is already present — a favorite follow-up variant.

  5. Question 5

    Which two statements about the SequencedMap operations of LinkedHashMap in Java 21 are correct? (Choose two.)

    1. A. sequencedKeySet() returns a SequencedSet<K>, and calling reversed() on it iterates the keys from last to first.Correct answer

      The key set of a sequenced map is ordered, so it is narrowed from Set to SequencedSet<K> and gains reversed(), which iterates the keys from last to first.

    2. B. putFirst(k, v) throws IllegalStateException when k is already present in the map.

      Invents a rejection rule. A positional put on an existing key moves the entry to the front and updates its value, returning the previous value, exactly like Map.put plus a reposition.

    3. C. pollFirstEntry() removes and returns the first entry, and returns null when the map is empty.Correct answer

      The poll/peek convention: pollFirstEntry() reads and removes the first entry, and signals an empty map by returning null rather than by throwing.

    4. D. sequencedValues() returns a SequencedSet<V> holding the values in encounter order.

      Confuses the view methods. Values are ordered but may repeat, so they cannot be a Set; sequencedValues() returns a SequencedCollection<V>, and only sequencedKeySet() returns a SequencedSet.

    Explanation

    `pollFirstEntry() removes and returns the first entry, and returns null when the map is empty.` — this is the poll/peek convention: `firstEntry()` reads, `pollFirstEntry()` reads *and* removes, and the poll methods signal emptiness with `null` rather than by throwing. `sequencedKeySet() returns a SequencedSet<K>, and calling reversed() on it iterates the keys from last to first.` — the key set of a sequenced map is itself ordered, so it is narrowed from `Set` to `SequencedSet` and gains `reversed()`, `getFirst()` and friends. Why the others are wrong: `sequencedValues() returns a SequencedSet<V>...` confuses the three view methods. Values are ordered but may repeat, so they cannot be a `Set`: `sequencedValues()` returns a `SequencedCollection<V>`. Only `sequencedKeySet()` returns a `SequencedSet`, and `sequencedEntrySet()` a `SequencedSet` of entries. `putFirst(k, v) throws IllegalStateException when k is already present...` invents a rejection rule. A positional put on an existing key *moves* the entry to the front and updates its value, returning the previous value — exactly like `Map.put`, plus a reposition. Exam tip: `first`/`last` + `Entry` gives you four map methods in a 2x2 grid — `firstEntry`/`lastEntry` read, `pollFirstEntry`/`pollLastEntry` remove. The reverse trap is the empty map: the *poll* pair returns `null`, whereas `getFirst()` on an empty `SequencedCollection` throws `NoSuchElementException`.

  6. Question 6

    addFirst() is called with an element the set already contains. What does this print? ```java import java.util.*; public class Main { public static void main(String[] args) { LinkedHashSet<String> s = new LinkedHashSet<>(List.of("a", "b", "c")); s.addFirst("c"); System.out.println(s + " " + s.size()); } } ```

    1. A. [a, b, c] 3

      Encodes the Set.add reflex that adding an already-present element is a no-op. addFirst carries a POSITION, so it moves the existing "c" to the head, giving [c, a, b].

    2. B. Throws UnsupportedOperationException

      Over-generalises the TreeSet rule. A LinkedHashSet has insertion order that positional insertion can honour, so it accepts addFirst; only sorted sets like TreeSet reject these positional writes.

    3. C. [c, a, b] 3Correct answer

      SequencedSet.addFirst repositions an already-present element rather than rejecting it, so LinkedHashSet unlinks the existing "c" and relinks it at the head, giving [c, a, b]; it remains a set, so size stays 3.

    4. D. [c, a, b, c] 4

      Treats the set as a list and inserts a second copy at the front. A LinkedHashSet never holds duplicates, so the size cannot rise; the existing "c" is moved, not duplicated.

    Explanation

    Trace: `SequencedSet.addFirst` is specified to *reposition* an element that is already present, not to reject it. `LinkedHashSet` therefore unlinks the existing `c` from the tail and relinks it at the head, leaving encounter order `[c, a, b]`. The set is still a set, so no duplicate appears and `size()` stays `3`. The output is `[c, a, b] 3`. Why the others are wrong: `[a, b, c] 3` encodes the `Set.add` reflex: "adding an element that is already present is a no-op, so nothing changes." That holds for plain `add`, but `addFirst` explicitly carries a *position*, and honouring that position means moving the element. `[c, a, b, c] 4` treats the set as a list and inserts a second copy at the front. A `LinkedHashSet` never holds duplicates, so the size can never rise here. `Throws UnsupportedOperationException` over-generalises the `TreeSet` rule. A `TreeSet` rejects `addFirst` because an explicit position would contradict its comparator ordering; a `LinkedHashSet` has insertion order, which positional insertion can honour, so it accepts the call. Exam tip: for the sequenced interfaces, an `addFirst`/`addLast`/`putFirst`/`putLast` on an element or key that is *already there* means **move it**, not duplicate it and not ignore it. The reverse trap is the sorted implementations — `TreeSet` and `TreeMap` throw `UnsupportedOperationException` for exactly these positional writes.

  7. Question 7

    A TreeSet is assigned to a SequencedSet variable. What happens when addFirst(x) is called on it?

    1. A. x is added as the first element if it is smaller than the current first

      Even a would-be-smallest element throws; the method never inspects the value before rejecting the positional insert.

    2. B. Compilation fails: TreeSet does not implement SequencedSet

      It compiles: TreeSet implements NavigableSet, which extends SortedSet, which extends SequencedSet in Java 21.

    3. C. It always throws UnsupportedOperationExceptionCorrect answer

      A sorted set's order comes from its comparator, so a caller cannot dictate that an arbitrary element be first; JEP 431 specifies SortedSet's addFirst/addLast always throw UnsupportedOperationException, regardless of the argument.

    4. D. The set is reordered so that x becomes first

      Sorted sets never let a caller override comparison order, so the element cannot be forced to the front.

    Explanation

    A sorted set's order is defined by its comparator, so a caller cannot force an arbitrary element to a particular end. JEP 431 therefore specifies that SortedSet's positional writes addFirst/addLast always throw UnsupportedOperationException, without even inspecting the argument. The positional read accessors like getFirst/getLast still work on sorted types; only the positional writes are unsupported.

  8. Question 8

    What does this print? ```java import java.util.*; public class Main { public static void main(String[] args) { SequencedCollection<Integer> c = new ArrayList<>(List.of(1, 2, 3)); c.addFirst(0); System.out.println(c.getFirst() + " " + c.getLast()); } } ```

    1. A. 0 3Correct answer

      Since Java 21 List extends SequencedCollection, so an ArrayList fits the variable and addFirst(0) prepends, giving [0, 1, 2, 3]; getFirst() is 0 and getLast() is 3.

    2. B. Compilation fails: ArrayList is not a SequencedCollection

      Assumes ArrayList is not a SequencedCollection, but List (and therefore ArrayList) implements SequencedCollection in Java 21, so the code compiles.

    3. C. 0 0

      This would require the list to contain only the prepended element; the original three elements are still present, so getLast() is 3, not 0.

    4. D. 1 3

      Ignores the addFirst(0) call, which makes 0 the new first element ahead of the original 1.

    Explanation

    In Java 21 the Collections Framework was retrofitted so `List` (and implementations like ArrayList) extends `SequencedCollection`, making `addFirst`, `getFirst`, and `getLast` available. Prepending an element makes it the new first while the existing tail is unchanged. Watch the mutability layer: `List.of(...)` is immutable, but here it is copied into a mutable ArrayList first, so `addFirst` succeeds — calling it directly on `List.of(...)` would throw UnsupportedOperationException.

Practise all 17 Sequenced Collections questions

OCP Java SE 21 has the full set, inside timed mock exams that mirror real exam conditions — every question with a worked explanation.

Open OCP Java SE 21

Other topics in this pack