Video in progress
Why does this code throw an exception?
List<String> roles = Arrays.asList("USER", "ADMIN", "GUEST");
roles.removeIf(r -> r.equals("GUEST"));
Arrays.asList returns a fixed-size list, which is a view over the array. When removeIf tries to remove an element, an UnsupportedOperationException is thrown.
📖 Answer
The class that Arrays.asList returns is not java.util.ArrayList but a private ArrayList nested inside Arrays. It extends AbstractList and does not override add/remove, and the default implementation throws an exception.
The interesting part: if no element matches the condition, removeIf doesn't throw, because it never tries to remove anything. So the error shows up with some data and not with other data, which makes it hard to track down.
The fix:
List<String> roles = new ArrayList<>(Arrays.asList("USER", "ADMIN", "GUEST"));
roles.removeIf(r -> r.equals("GUEST"));
Or build a new list without modifying the old one:
List<String> active = roles.stream().filter(r -> !r.equals("GUEST")).toList();
Sign up to mark studied questions and save your progress.