Calling remove() on ArrayList throws Exception java.lang.UnsupportedOperationException at java.util.AbstractList.remove(AbstractList.java:161)

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

import java.util.Arrays;
import java.util.List;

public class Main {

    public static void main(String[] args) throws Exception {
        List<String> names = getNames();
        names.remove(0);
    }

    private static List<String> getNames() {
        return Arrays.asList("Amir", "Arnie", "Beth", "Lucy");
    }
}

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"));
}