Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am unable to add an element to a list? UnsupportedOperationException

Tags:

This one list object is biting me in the butt..

Any time I try to add an element to it, it produces this:

Caused by: java.lang.UnsupportedOperationException
        at java.util.AbstractList.add(AbstractList.java:148)
        at java.util.AbstractList.add(AbstractList.java:108)

The line producing the error is insignificant, but here it is anyways:

AdventureLobbies.players.add(args[0].toLowerCase());

Should I not be accessing it statically?

Actual declaration of variable:

AdventureLobbies.players = Arrays.asList(rs.getString("players").toLowerCase().split(","));

Any ideas? Can't find anything on Google that's worthwhile.

like image 241
Gray Adams Avatar asked Apr 08 '12 00:04

Gray Adams


People also ask

How do I resolve UnsupportedOperationException in Java?

The UnsupportedOperationException can be resolved by using a mutable collection, such as ArrayList , which can be modified. An unmodifiable collection or data structure should not be attempted to be modified.

Can I add element to List Java?

There are two methods to add elements to the list. add(E e): appends the element at the end of the list. Since List supports Generics, the type of elements that can be added is determined when the list is created. add(int index, E element): inserts the element at the given index.

How do I add an element to a List object in Java?

You insert elements (objects) into a Java List using its add() method. Here is an example of adding elements to a Java List using the add() method: List<String> listA = new ArrayList<>(); listA. add("element 1"); listA.

What is List of () in Java?

List in Java provides the facility to maintain the ordered collection. It contains the index-based methods to insert, update, delete and search the elements. It can have the duplicate elements also. We can also store the null elements in the list.


2 Answers

Arrays.asList() will give you back an unmodifiable list, and that is why your add is failing. Try creating the list with:

AdventureLobbies.players = new ArrayList(Arrays.asList(rs.getString("players").toLowerCase().split(",")));
like image 198
John Farrelly Avatar answered Sep 20 '22 17:09

John Farrelly


The java docs say asList @SafeVarargs public static <T> List<T> asList(T... a) "Returns a fixed-size list backed by the specified array"

Your list is fixed size, meaning it cannot grow or shrink and so when you call add, it throws an unsupported operation exception

like image 40
user12345613 Avatar answered Sep 20 '22 17:09

user12345613