Skip to main content
  1. blog/

Calling remove() on ArrayList throws UnsupportedOperationException

·1 min

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package com.steelcityamir.app;

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