Java List.add() UnsupportedOperationException [英] Java List.add() UnsupportedOperationException

查看:33
本文介绍了Java List.add() UnsupportedOperationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将对象添加到 List 实例,但它抛出一个 UnsupportedOperationException.有谁知道为什么?

我的 Java 代码:

String[] membersArray = request.getParameterValues('members');列表<字符串>membersList = Arrays.asList(membersArray);for(字符串成员:成员列表){Person person = Dao.findByName(member);列表<字符串>也可以看看;seeAlso = person.getSeeAlso();如果 (!seeAlso.contains(groupDn)){参见Also.add(groupDn);person.setSeeAlso(seeAlso);}}

错误信息:

<前>java.lang.UnsupportedOperationExceptionjava.util.AbstractList.add(来源不明)java.util.AbstractList.add(来源不明)javax.servlet.http.HttpServlet.service(HttpServlet.java:641)javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

解决方案

并非每个 List 实现支持 add() 方法.

一个常见的例子是 Arrays.asList():据记载支持任何结构修改(即删除或添加元素)(强调我的):

<块引用>

返回由指定数组支持的固定大小列表.

即使这不是您要修改的特定 List,答案仍然适用于其他不可变或仅允许某些选定更改的 List 实现.

您可以通过阅读UnsupportedOperationException 的文档来了解这一点List.add(),将其记录为(可选操作)".List 文档的顶部解释了该短语的确切含义.

作为一种解决方法,您可以创建一个列表副本到一个已知的可修改实现,例如 ArrayList:

seeAlso = new ArrayList<>(seeAlso);

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)

解决方案

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);

这篇关于Java List.add() UnsupportedOperationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆