- Amir Boroumand | Software engineer based in Pittsburgh, PA/
- blog/
- Calling remove() on ArrayList throws UnsupportedOperationException/
Calling remove() on ArrayList throws UnsupportedOperationException
Overview #
In this article, I’ll cover one of the nuances in the Java Collections Framework when creating ArrayList
objects.
I ran into this runtime exception recently while attempting to remove an element from an ArrayList
in Java, and it puzzled me for a few minutes.
Code #
Here is some sample code that demonstrates the issue.
|
|
Output #
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
at Main.main(Main.java:10)
The getNames()
method returns an ArrayList so why is the remove()
operation throwing an exception?
The static method called on line 13 Arrays.asList
returns an instance of java.util.Arrays$ArrayList
which is a nested class inside the Arrays class that implements the List interface. This particular implementation has a fixed size.
This is actually different than what I expected it to return which was the standard java.util.ArrayList
.
The solution is to use the constructor to create the list:
private static List<String> getNames() {
return new ArrayList<>(Arrays.asList("Amir", "Arnie", "Beth", "Lucy"));
}