Java / Java 21 Collection Framework features Interview questions
How do you use getFirst() and getLast() on an ArrayList in Java 21?
Since ArrayList implements List, which now extends SequencedCollection, you can call getFirst() and getLast() directly on any ArrayList instance without any casting or extra setup.
ArrayList<String> fruits = new ArrayList<>(List.of("apple", "banana", "cherry")); System.out.println(fruits.getFirst()); // apple System.out.println(fruits.getLast()); // cherry
This reads more clearly than fruits.get(0) and fruits.get(fruits.size() - 1), and it avoids the classic off-by-one mistake of forgetting to subtract 1 from size().
Both throw NoSuchElementException if the list is empty, so guard with isEmpty() when the list might have no elements.
More Related questions...