Java List.add()UnsupportedOperationException [英] Java List.add() UnsupportedOperationException
问题描述
我尝试将对象添加到 List< String>
实例中,但它会引发 UnsupportedOperationException
。
有没有人知道为什么?
I try to add objects to a List<String>
instance but it throws an UnsupportedOperationException
.
Does anyone know why?
我的Java代码:
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);
}
}
错误信息:
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)
推荐答案
不是每个 列表
实现支持 add()
方法。
一个常见的例子是由列表 docs / api / java / util / Arrays.html#asList%28T ...%29> Arrays.asList()
: > 支持任何结构修改(即删除或添加元素)(强调我的):
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.
即使这不是具体的列表 code>您正在尝试修改,答案仍然适用于其他
列表
实现,不可变或只允许一些选定的更改。
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.
您可以通过阅读 UnsupportedOperationException
和 List.add()
,将其记录为(可选操作)。这个短语的确切含义在列表
文档的顶部进行了说明。
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.
作为解决方法,您可以创建列表的副本到已知可修改的实现,如 ArrayList
:
As a workaround you can create a copy of the list to a known-modifiable implementation like ArrayList
:
seeAlso = new ArrayList<>(seeAlso);
这篇关于Java List.add()UnsupportedOperationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!