How to Fix Unsupported Operation Exception on List add() in Java
We might find ourselves encountering this UnsupportedOperationException
when calling the add()
method on a list.
List<Integer> list = Arrays.asList(1,2,3);
list.add(4);
The above code will throw this UnsupportedOperationException
error.
java.lang.UnsupportedOperationException
java.util.AbstractList.add(Unknown Source)
java.util.AbstractList.add(Unknown Source)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Why UnsupportedOperation
is thrown
Some List
implementations do not support our standard add()
and remove()
methods to modify the list.
As we’ve seen, Arrays.asList()
is one of these implementations.
asList()
creates a fixed-size list initialized to contain the elements passed in as parameters. The list created is backed by an array and is not an ArrayList
or LinkedList
, so the size cannot change.
It generally serves as a bridge between arrays and collections.
There are several use cases for asList()
:
We can use it to pass data into functions expecting collections.
void methodExpectingCollection(List<Integer> strings) { /*...*/ }
methodExpectingCollection(Arrays.asList(1,2,3));
We can also use it to create collections from arrays.
List<Integer> list = new ArrayList<Integer>(Arrays.asList(1,2,3));
Set<Integer> set = new HashSet<Integer>(Arrays.asList(1,2,3));
Fix using the ArrayList
constructor
As you might’ve seen above, we can fix this error by initializing an ArrayList
from the asList()
list.
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1,2,3));
Fix using the Stream API
We can also use the Stream API if we’re using Java 8+.
ArrayList<String> list = Stream.of(1,2,3)
.collect(Collectors.toCollection(ArrayList::new));