如何从集合中删除项目?
final Set<Expression> exps = meng.getExps();
Iterator<Expression> iterator = exps.iterator();
final Expression displayedExp = exps.iterator().next();
exps.remove(displayedExp);
此代码将返回以下运行时异常跟踪:
null
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.remove(Collections.java:1021)
meng.getExps() 的 Set 实现是 LinkedHashSet。
final Set<Expression> exps = meng.getExps();
Iterator<Expression> iterator = exps.iterator();
final Expression displayedExp = exps.iterator().next();
exps.remove(displayedExp);
This code would return the following run-time exceptions trace:
null
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.remove(Collections.java:1021)
The Set implementation of meng.getExps() is a LinkedHashSet.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
抱歉,您不走运:该集合包含 Collections.unmodifyingCollection,它正是这样做的:使集合不可修改。您唯一能做的就是将内容复制到另一个集中并使用它。
Sorry, you are out of luck: The Set was wrapped with Collections.unmodifiableCollection, which does exactly this: making the collection unmodifiable. The only thing you can do is copy the content into another Set and work with this.
您的 getter 显式地返回一个
UnmodifyingCollection
,它是一个围绕Set
的包装器,可防止修改。换句话说,API 是在告诉您“这是我的收藏,请看但不要碰!”
如果你想修改它,你应该将它复制到一个新的Set中。
HashSet
的复制构造函数非常适合此目的。Your getter is explicitly returning you an
UnmodifiableCollection
, which is a wrapper of sorts aroundSet
s that prevents modification.In other words, the API is telling you "this is my collection, please look but don't touch!"
If you want to modify it, you should copy it into a new Set. There are copying constructors for
HashSet
that are great for this purpose.您将您的集合声明为“最终”,这意味着它无法修改。您收到的错误是正常的。
如果要更改 Set 的内容,请删除“final”。
You declared your Set as 'final', which means that it can not be modified. The error you get is normal.
If you want to change the content of the Set, remove 'final'.