Java / Java 21 Collection Framework features Interview questions
What happens when you call getFirst() on an empty SequencedCollection?
It throws a NoSuchElementException, the same exception Deque.getFirst() and Deque.getLast() have always thrown when called on an empty deque.
List<String> empty = new ArrayList<>(); empty.getFirst(); // throws NoSuchElementException
This is different from methods like peekFirst() on Deque, which return null instead of throwing, and different from firstEntry() on SequencedMap, which also returns null rather than throwing.
Because of this, code that isn't certain a collection is non-empty should guard the call with isEmpty(), or catch the exception explicitly, rather than assuming getFirst() will fail gracefully.
More Related questions...