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

早过忘川 提交于 2019-11-27 23:18:03

问题


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.


回答1:


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(",")));



回答2:


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




回答3:


This exception is very familiar with accessing objects that will not permit the access according to java language rules like accessing immutable objects, for that reason instantiate it in the following way instead:

AdventureLobbies.players = new ArrayList(Arrays.
asList(rs.getString("players").toLowerCase().split(","))); // Perfectly done


来源:https://stackoverflow.com/questions/10059395/i-am-unable-to-add-an-element-to-a-list-unsupportedoperationexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!