Java / Java 21 Collection Framework features Interview questions
How do you troubleshoot UnsupportedOperationException when calling addFirst() on an unmodifiable list?
This exception means the list you're calling addFirst() on doesn't support structural modification - commonly a list created with List.of(...), Collections.unmodifiableList(...), or the fixed-size list returned by Arrays.asList(...).
List<String> frozen = List.of("a", "b"); frozen.addFirst("z"); // throws UnsupportedOperationException
The fix is to work with a genuinely mutable copy instead of the immutable original: wrap it in a new ArrayList before mutating.
List<String> mutable = new ArrayList<>(frozen); mutable.addFirst("z"); // works fine
If the list came from somewhere else in your codebase (a method return value, a field), trace back where it was created to confirm whether it's meant to be immutable by design - forcing mutability onto a list that was deliberately made immutable usually indicates the calling code, not the list, needs to change.
More Related questions...