- Amir Boroumand | Software Engineer based in Pittsburgh, PA/
- blog/
- Why Removing an Element from an ArrayList in Java Can Throw UnsupportedOperationException/
Why Removing an Element from an ArrayList in Java Can Throw UnsupportedOperationException
Overview #
In this article, we’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.
Below is some sample code that demonstrates the issue.
Code #
|
|
Output #
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
at Main.main(Main.java:8)
The getNames()
method returns an ArrayList
so why is the remove()
operation throwing an exception?
The static method called on line 12 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"));
}