Java / Java 21 Collection Framework features Interview questions
Explain the lifecycle of a view returned by SequencedMap.reversed()?
When you call reversed() on a SequencedMap, the JDK constructs a new, lightweight SequencedMap wrapper object whose lifetime is tied entirely to the original map - it holds a reference back to it rather than copying any entries.
flowchart TD
A["map.reversed() called"] --> B["New reversed-view object created"]
B --> C["View delegates reads/writes to original map"]
C --> D{"Original map mutated?"}
D -->|Yes| E["Change instantly visible through the view"]
D -->|No| F["View reflects unchanged state"]
E --> G["View remains valid until original map is discarded"]
F --> G
The view has no independent lifecycle of its own beyond ordinary garbage collection - once nothing references it, it's collected like any other object, and it never needs explicit closing or disposal.
If the original map is structurally modified while iterating the reversed view (without going through the view's own iterator), it can trigger a ConcurrentModificationException on the next access, exactly as it would for the original map's own iterator - the reversed view doesn't get any special exemption from fail-fast behavior.
More Related questions...