How to delete an item from a Set?
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.UnsupportedOperationE开发者_StackOverflow社区xception
at java.util.Collections$UnmodifiableCollection.remove(Collections.java:1021)
The Set implementation of meng.getExps() is a LinkedHashSet.
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.
Your getter is explicitly returning you an UnmodifiableCollection
, which is a wrapper of sorts around Set
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.
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'.
精彩评论