添加列表抛出java.lang.UnsupportedOperationException
我有4个函数使用相同的get…()方法,我只更改了名称或标识符,但第四个函数的结果不同,即当向列表添加新项时,它抛出java.lang.UnsupportedOperationException。我向你保证,我已经仔细检查了所有4个函数及其关系,但不知道为什么第四个函数会这样添加列表抛出java.lang.UnsupportedOperationException,java,unsupportedoperation,Java,Unsupportedoperation,我有4个函数使用相同的get…()方法,我只更改了名称或标识符,但第四个函数的结果不同,即当向列表添加新项时,它抛出java.lang.UnsupportedOperationException。我向你保证,我已经仔细检查了所有4个函数及其关系,但不知道为什么第四个函数会这样 public List<PropertyAttribute> getAttributes() { if (selectedCode == null) return null;
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;
}
除非有明确的文档记录,否则不要认为修改从其他方法收到的列表是安全的。即使它没有抛出异常,它也可能在改变临界状态(如果它没有安全地实现的话)。将其复制到新列表中,您可以执行任何您喜欢的操作:
List<PropertyAttribute> list = new ArrayList<>(criteria.list());
List List=newarraylist(criteria.List());
您可以发布整个stackTrace吗?了解哪个List
实现criteria.List()
producei可能会像@nbokmans一样猜测criteria.List()
使用Arrays.asList()
(或等效)返回不支持add
操作的实例,很明显问题出在哪里。以及给出的解决方案。@AxelH谢谢,我会看到的。它很有效。但是你能告诉我为什么其他3个函数没有抛出异常吗?我没有看到任何其他函数。
List<PropertyAttribute> list = new ArrayList<>(criteria.list());