Java / Java 21 Collection Framework features Interview questions
How is the encounter order of a LinkedHashSet determined when using SequencedSet methods?
A LinkedHashSet's encounter order is, by default, the order in which elements were inserted - the first element added (that's still present) is what getFirst() returns, and the most recently added element is what getLast() returns.
LinkedHashSet<String> tags = new LinkedHashSet<>(); tags.add("java"); tags.add("collections"); System.out.println(tags.getFirst()); // java
Re-adding an element that's already present does not move it - Set.add() is a no-op for duplicates, so the original insertion position is preserved unless the element is explicitly removed and re-added.
Calling addFirst() or addLast() on the set inserts a new element at the requested end, but if that element already exists elsewhere in the set, it's first removed from its old position and then reinserted at the new end, since a Set can't contain the same element twice.
More Related questions...