Why do I get an UnsupportedOperationException when trying to remove an element from a List?
The java.lang.UnsupportedOperationException
is thrown when an operation is not supported by a class. In the case of a List
, this exception is typically thrown when you try to modify the list using one of the remove
, add
, or set
methods, and the list is unmodifiable.
A list is considered unmodifiable when it cannot be modified, either because it is a fixed-size list, or because it is a view of another list that is not modifiable.
For example, the java.util.Arrays.asList()
method returns a fixed-size list that is a view of an array. This list is unmodifiable, and any attempt to modify it will result in an UnsupportedOperationException
.
Here is an example of how you can get an UnsupportedOperationException
when trying to remove an element from a list:
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "b", "c");
list.remove(1); // This will throw an UnsupportedOperationException
}
}
To fix this issue, you can create a new modifiable list from the unmodifiable list, using the java.util.ArrayList
constructor.
For example:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> unmodifiableList = Arrays.asList("a", "b", "c");
List<String> list = new ArrayList<>(unmodifiableList);
list.remove(1); // This will remove the element at index 1
}
}
This will create a new modifiable ArrayList from the unmodifiable list, and allow you to remove elements from the list without getting an UnsupportedOperationException
.