Java List.add() UnsupportedOperationException

a11r picture a11r · Apr 22, 2011 · Viewed 161.3k times · Source

I try to add objects to a List<String> instance but it throws an UnsupportedOperationException. Does anyone know why?

My Java code:

String[] membersArray = request.getParameterValues('members');
List<String> membersList = Arrays.asList(membersArray);

for (String member : membersList) {
    Person person = Dao.findByName(member);
    List<String> seeAlso;
    seeAlso = person.getSeeAlso();
    if (!seeAlso.contains(groupDn)){
        seeAlso.add(groupDn);
        person.setSeeAlso(seeAlso);
    }
}

The error message:

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)

Answer

Joachim Sauer picture Joachim Sauer · Apr 22, 2011

Not every List implementation supports the add() method.

One common example is the List returned by Arrays.asList(): it is documented not to support any structural modification (i.e. removing or adding elements) (emphasis mine):

Returns a fixed-size list backed by the specified array.

Even if that's not the specific List you're trying to modify, the answer still applies to other List implementations that are either immutable or only allow some selected changes.

You can find out about this by reading the documentation of UnsupportedOperationException and List.add(), which documents this to be an "(optional operation)". The precise meaning of this phrase is explained at the top of the List documentation.

As a workaround you can create a copy of the list to a known-modifiable implementation like ArrayList:

seeAlso = new ArrayList<>(seeAlso);