Java / Java 21 Collection Framework features Interview questions
Define encounter order in the context of Sequenced Collections?
Encounter order is the sequence in which a collection's elements are visited when you iterate over it - it defines which element is "first" and which is "last" for that collection.
Some collections have a well-defined encounter order by design: a List follows index order, a LinkedHashSet/LinkedHashMap follows insertion order, and a TreeSet/TreeMap follows the ordering defined by a Comparator or natural ordering.
Others, like HashSet and HashMap, have no defined encounter order - their iteration order depends on hash bucket placement and can change between JVM runs. That's exactly why the Sequenced interfaces are retrofitted only onto types with a real, defined order.
More Related questions...