🔧 Error Fixes
· 1 min read

Java UnsupportedOperationException — How to Fix It


java.lang.UnsupportedOperationException
at java.util.AbstractList.add

You’re trying to modify a collection that doesn’t support modification — usually created by Arrays.asList(), List.of(), or Collections.unmodifiableList().

Fix 1: Arrays.asList Returns Fixed-Size List

// ❌ Can't add/remove from Arrays.asList
List<String> list = Arrays.asList("a", "b", "c");
list.add("d");  // 💥

// ✅ Wrap in ArrayList
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
list.add("d");  // Works

Fix 2: List.of Returns Immutable List

// ❌ List.of() is immutable (Java 9+)
List<String> list = List.of("a", "b");
list.add("c");  // 💥

// ✅ Create mutable copy
List<String> list = new ArrayList<>(List.of("a", "b"));

Fix 3: Collections.unmodifiableList

// ❌ Explicitly unmodifiable
List<String> list = Collections.unmodifiableList(original);
list.set(0, "new");  // 💥

// ✅ Modify the original, or create a new mutable copy
List<String> mutable = new ArrayList<>(list);
mutable.set(0, "new");

Fix 4: Stream Collect to Mutable List

// ❌ Collectors.toUnmodifiableList() (Java 10+)
List<String> list = items.stream()
    .filter(x -> x.length() > 3)
    .collect(Collectors.toUnmodifiableList());
list.add("new");  // 💥

// ✅ Use toList() or ArrayList collector
List<String> list = items.stream()
    .filter(x -> x.length() > 3)
    .collect(Collectors.toCollection(ArrayList::new));

Fix 5: Map.of Is Also Immutable

// ❌ Map.of() is immutable
Map<String, Integer> map = Map.of("a", 1);
map.put("b", 2);  // 💥

// ✅ Wrap in HashMap
Map<String, Integer> map = new HashMap<>(Map.of("a", 1));