如何从Set中删除项目?

sim*_*ico 7 java collections

final Set<Expression> exps = meng.getExps();
Iterator<Expression> iterator = exps.iterator();
final Expression displayedExp = exps.iterator().next();
exps.remove(displayedExp);
Run Code Online (Sandbox Code Playgroud)

此代码将返回以下运行时异常跟踪:

null
java.lang.UnsupportedOperationException
        at java.util.Collections$UnmodifiableCollection.remove(Collections.java:1021)
Run Code Online (Sandbox Code Playgroud)

meng.getExps()的Set实现是一个LinkedHashSet.

Lan*_*dei 7

对不起,你运气不好:Set用Collections.unmodifiableCollection包装,它完全正确:使集合不可修改.您唯一能做的就是将内容复制到另一个Set中并使用它.