Java / Java 21 Collection Framework features Interview questions
When would you choose getFirst() over get(0) on a List?
Choose getFirst() whenever you're writing code that should read clearly and work uniformly across any SequencedCollection, not just lists - it says "give me the first element" without hardcoding an assumption about indexing.
get(0) only exists on List, so code that uses it can never be generalized to work on an ArrayDeque or a LinkedHashSet without changing the method call entirely. getFirst(), on the other hand, works unchanged if you later swap the concrete type or widen the declared type to SequencedCollection.
There's essentially no performance difference for ArrayList, since getFirst() is implemented internally as a direct index lookup. For LinkedList, both are already O(1) at the ends, so the choice there is purely about readability and API generality rather than speed.
More Related questions...