java 我无法将元素添加到列表中?不支持的操作异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10059395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I am unable to add an element to a list? UnsupportedOperationException
提问by Gray Adams
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(","));
AdventureLobbies.players = Arrays.asList(rs.getString("players").toLowerCase().split(","));
Any ideas? Can't find anything on Google that's worthwhile.
有任何想法吗?在谷歌上找不到任何有价值的东西。
回答by John Farrelly
Arrays.asList() will give you back an unmodifiable list, and that is why your add is failing. Try creating the list with:
Arrays.asList() 会给你一个不可修改的列表,这就是你添加失败的原因。尝试使用以下方法创建列表:
AdventureLobbies.players = new ArrayList(Arrays.asList(rs.getString("players").toLowerCase().split(",")));
回答by user12345613
The java docs say
asList
@SafeVarargs
public static <T> List<T> asList(T... a)
"Returns a fixed-size list backed by the specified array"
java 文档说
asList
@SafeVarargs
public static <T> List<T> asList(T... a)
“返回由指定数组支持的固定大小列表”
Your list is fixed size, meaning it cannot grow or shrink and so when you call add, it throws an unsupported operation exception
你的列表是固定大小的,这意味着它不能增长或缩小,所以当你调用 add 时,它会抛出一个不受支持的操作异常
回答by GingerHead
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:
这个异常对于访问不允许根据 java 语言规则访问的对象(例如访问不可变对象)非常熟悉,因此请按以下方式实例化它:
AdventureLobbies.players = new ArrayList(Arrays.
asList(rs.getString("players").toLowerCase().split(","))); // Perfectly done