Quiz: Sequenced Collections
Study the lesson first: Sequenced Collections
Total: 7 questions
1. What are Sequenced Collections in Java and in which version did they appear?
What are Sequenced Collections in Java and in which version did they appear?
Sequenced Collections (JEP 431) are three interfaces in java.util, added in Java 21 directly as a final feature, without preview: SequencedCollection, SequencedSet and SequencedMap. They describe collections with a defined encounter order, which have a first and a last element.
Before Java 21 there was no common type for an ordered collection, and the same operation had different names: the last element was list.get(list.size() - 1) for a list, getLast() for a Deque, last() for a TreeSet, and for a LinkedHashSet only a full traversal. Now all ordered collections share the same methods: getFirst(), getLast(), addFirst(), addLast(), removeFirst(), removeLast() and reversed(). Maps get firstEntry(), lastEntry(), pollFirstEntry(), pollLastEntry(), putFirst(), putLast(), reversed() and the ordered views sequencedKeySet(), sequencedValues(), sequencedEntrySet().
The old methods (first(), descendingSet(), descendingIterator()) remain and work as before. Java 17 and earlier do not have the new interfaces, and list.getFirst() does not compile there.
2. Which collections implement SequencedCollection, SequencedSet and SequencedMap, which do not, and why?
Which collections implement SequencedCollection, SequencedSet and SequencedMap, which do not, and why?
JEP 431 inserted the new interfaces between existing levels of the hierarchy:
SequencedCollectionextendsCollectionand became the parent ofListandDeque, so it is implemented byArrayList,LinkedList,Vector,CopyOnWriteArrayList,ArrayDeque,LinkedBlockingDeque,ConcurrentLinkedDeque.SequencedSetextendsSequencedCollectionandSet. It is implemented byLinkedHashSet(insertion order) and, throughSortedSet, byTreeSetandConcurrentSkipListSet(sort order).SequencedMapextendsMap. It is implemented byLinkedHashMapand, throughSortedMap, byTreeMapandConcurrentSkipListMap.
Collections without a defined order do not implement them: HashSet, HashMap, EnumSet, CopyOnWriteArraySet, IdentityHashMap. The iteration order of a HashSet depends on hash codes and table capacity and can change after insertions, so a "first element" means nothing. PriorityQueue does not implement them either: it is a Queue, not a Deque, and its iterator does not traverse elements in priority order. For insertion order use LinkedHashSet and LinkedHashMap, for sorting use TreeSet and TreeMap.
3. What does the reversed() method return, and does it copy the collection?
What does the reversed() method return, and does it copy the collection?
reversed() does not copy the collection or rearrange its elements. In O(1) it returns a view that reads the source collection from the other end. Changes to the source collection are visible in the view right away, and changes through the view go to the original: add() at the end of a list view inserts the element at the start of the source list, set(0, x) replaces the last element.
The return type is refined down the hierarchy: List for a List, Deque for a Deque, SequencedSet for a LinkedHashSet, NavigableSet for a TreeSet, NavigableMap for a TreeMap, LinkedList for a LinkedList. So after reversed() the usual methods of the type are available, such as get(int) on a list.
The typical use is iterating from the end: for (var x : list.reversed()). An independent reversed copy is new ArrayList<>(list.reversed()). Do not confuse it with Collections.reverse(list): that rearranges the elements of the list itself and returns nothing. On unmodifiable collections reversed() works for reading (List.of(1, 2, 3).reversed() gives [3, 2, 1]), while writing through the view throws UnsupportedOperationException.
4. How do SequencedMap methods differ from SequencedCollection methods?
How do SequencedMap methods differ from SequencedCollection methods?
A map is not a collection, so SequencedMap has its own methods that work with Map.Entry pairs: firstEntry(), lastEntry(), pollFirstEntry(), pollLastEntry(), putFirst(k, v), putLast(k, v), reversed() and the views sequencedKeySet(), sequencedValues(), sequencedEntrySet(). The main differences:
- An empty map gives
null, not an exception.firstEntry()andpollFirstEntry()returnnullon an empty map (behavior inherited fromNavigableMap), whilegetFirst()on an empty collection throwsNoSuchElementException. - The pair from
firstEntry()is an immutable snapshot. It does not see later changes to the map, andsetValue()on it throwsUnsupportedOperationException- for bothTreeMapandLinkedHashMap. To change the value of the first pair usemap.put(map.firstEntry().getKey(), v)ormap.sequencedEntrySet().getFirst().setValue(v): entries fromentrySetare live. putFirst()andputLast()move an existing key to the start or end in aLinkedHashMap, but throwUnsupportedOperationExceptionin aTreeMap, because the keys define the order there.- You cannot add to the views
sequencedKeySet(),sequencedValues(),sequencedEntrySet()(addFirst()throws an exception), but reading and removing work.
5. When do Sequenced interface methods throw NoSuchElementException and UnsupportedOperationException?
When do Sequenced interface methods throw NoSuchElementException and UnsupportedOperationException?
NoSuchElementException - when there is no element: getFirst(), getLast(), removeFirst(), removeLast() on an empty collection. For comparison, list.get(0) on an empty list throws IndexOutOfBoundsException, and peekFirst() on a Deque returns null. The Sequenced collection methods have no null-returning variant, so check isEmpty() before getFirst().
UnsupportedOperationException - when the collection does not allow the operation. Add and remove methods are optional operations:
List.of(),stream.toList(),Collections.unmodifiable*()- any modification is forbidden;Arrays.asList()- the size cannot change (removeFirst(),addLast()), butset(), including throughreversed(), works;TreeSetandTreeMap-addFirst(),addLast(),putFirst(),putLast()are forbidden because the comparator defines the position of an element;removeFirst()andpollFirstEntry()work;sequencedKeySet(),sequencedValues(),sequencedEntrySet()- you cannot add, but you can remove.
Reading (getFirst(), getLast(), reversed()) is allowed on all of these collections. For unmodifiable wrappers that keep the Sequenced methods, Java 21 added Collections.unmodifiableSequencedCollection(), unmodifiableSequencedSet() and unmodifiableSequencedMap().
6. Why use SequencedCollection as a parameter or variable type?
Why use SequencedCollection as a parameter or variable type?
Before Java 21 a method that returns the first and last element had to be written separately for List, Deque and SortedSet, or accept a Collection and hope it had an order. Now one parameter is enough:
static <T> String ends(SequencedCollection<T> items) {
return items.isEmpty() ? "empty" : items.getFirst() + ".." + items.getLast();
}
Such a method accepts a List, ArrayDeque, LinkedHashSet, TreeSet, while the compiler rejects a HashSet - the mistake is caught at compile time, not while the program runs.
The compiler looks at the declared type, not at the class of the object: a variable Set<String> s = new LinkedHashSet<>() has no getFirst() and cannot be passed to a method with a SequencedCollection parameter. The rule for choosing a type is the same as before - the most general type that is enough: for iteration, Collection or Iterable; for "first, last, from the end", SequencedCollection, SequencedSet or SequencedMap.
7. What can break when moving to Java 21 because of Sequenced Collections?
What can break when moving to Java 21 because of Sequenced Collections?
For ordinary code the move is invisible: the new methods are default interface methods, and the old ones work as before. Problems appear in a few cases:
- The code is built for Java 17 or earlier.
list.getFirst()andlist.reversed()givecannot find symbol. Libraries that must build on old versions stay withlist.get(0)andlist.get(list.size() - 1). - Your class already has a method with the same name but a different type. An
ArrayListsubclass withOptional<String> getFirst()compiled on Java 17, but on Java 21 it gets the errorgetFirst() in MyList cannot implement getFirst() in List. The method has to be renamed. - A class implements both
ListandDeque. Both interfaces declarereversed()with different types, and without its own override the compiler reportsboth define reversed(), but with unrelated return types. The JDK solves this inLinkedList: itsreversed()returnsLinkedList, which fits both types. - Kotlin on Android. When compiled with JDK 21, calls to
removeFirst()andremoveLast()on aMutableListbind to the newjava.util.Listmethods, and on devices that lack them at run time the app crashes withNoSuchMethodError. The safe replacement isremoveAt(0)andremoveAt(lastIndex).