【问题标题】:Add List Throws java.lang.UnsupportedOperationException [duplicate]添加列表抛出 java.lang.UnsupportedOperationException [重复]
【发布时间】:2017-09-29 16:56:32
【问题描述】:

我有 4 个具有相同 get...() 方法的函数,我只更改名称或标识符,但我得到了与第四个不同的结果,即何时将新项目添加到列表中,它会抛出 java.lang. lang.UnsupportedOperationException。我向你保证,我已经仔细检查了所有 4 个函数及其关系,但不知道为什么第四个函数会这样。

public List<PropertyAttribute> getAttributes() {
    if (selectedCode == null)
        return null;

    Criteria criteria = this.propertyAttributeDAO.createCriteria();
    FilterUtils.byField(criteria, "propertyCode", this.selectedCode, true);
    List<PropertyAttribute> list = criteria.list();

    if (isNewAttribute()) {
        list.add(0, this.curAttribute); //this line that throws exception
    }

    return list;
}

更新堆栈跟踪:

Caused by: java.lang.UnsupportedOperationException
        at java.util.AbstractList.add(AbstractList.java:148)
        at bos.web.pages.instrument.ViewProperty.getAttributes(ViewProperty.java:654)
        at $InternalPropertyConduit_237587e282284.get(Unknown Source)
        at org.apache.tapestry5.internal.bindings.PropBinding.get(PropBinding.java:59)

【问题讨论】:

  • 你能发布整个stackTrace吗?了解List 实现criteria.list() 产生的可能也很有趣
  • 我猜想@nbokmans criteria.list() 使用 Arrays.asList()(或等效项)返回不支持 add 操作的实例。
  • 那你就有答案了,看AbstractList documention,问题出在哪里就很明显了。并给出了解决方案。
  • @AxelH 谢谢,会看到的。

标签: java unsupportedoperation


【解决方案1】:

除非有明确的记录,否则不要认为修改从其他方法收到的列表是安全的。即使它没有抛出异常,它也可能正在改变临界状态(如果它没有安全地实现)。将其复制到新列表中,您就可以为所欲为:

List<PropertyAttribute> list = new ArrayList<>(criteria.list());

【讨论】:

  • 它有效。但是你能告诉我为什么其他 3 个函数没有抛出异常吗?
  • 我没有看到任何其他功能。
猜你喜欢
  • 2017-09-28
  • 2020-06-15
  • 1970-01-01
  • 2019-10-24
  • 2021-04-26
  • 1970-01-01
  • 1970-01-01
  • 2019-01-02
  • 1970-01-01
相关资源
最近更新 更多