Java / Java 21 Collection Framework features Interview questions
Explain the internal working of the reversed() view for a List?
reversed() does not copy elements or allocate a new backing array; it returns a lightweight wrapper object that delegates every call back to the original list, translating indexes as it goes.
Internally, a call like reversedList.get(i) is translated to originalList.get(size - 1 - i) on the underlying list, so reads happen directly against the original data with a simple index flip rather than any traversal or copying.
flowchart LR
A["reversedList.get(i)"] --> B["Compute size - 1 - i"]
B --> C["originalList.get(size-1-i)"]
C --> D["Return element"]
Mutating operations follow the same translation: reversedList.addFirst(e) is delegated as originalList.addLast(e), and reversedList.removeLast() is delegated as originalList.removeFirst(), keeping both views permanently in sync since they share the exact same backing storage.
Because it's O(1) to construct and each operation is a constant-time delegation, calling reversed() repeatedly, or even chaining list.reversed().reversed(), costs essentially nothing beyond the small wrapper allocation.
More Related questions...