Java / Java 21 Collection Framework features Interview questions
What are addFirst() and addLast() used for?
addFirst(E) inserts an element at the beginning of a sequenced collection, and addLast(E) inserts one at the end, updating the encounter order accordingly.
These were already familiar from Deque, but Java 21 makes them available on any type that implements SequencedCollection, including ArrayList and LinkedList.
List<String> tasks = new ArrayList<>(List.of("write", "test")); tasks.addFirst("plan"); tasks.addLast("deploy"); // [plan, write, test, deploy]
On a fixed-size or unmodifiable list, both methods throw UnsupportedOperationException, since inserting elements would change the list's size.
More Related questions...