How to remove 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 will return the following exception trace at runtime:

 null java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableCollection.remove(Collections.java:1021) 

The implementation of Set meng.getExps () is a LinkedHashSet.

+7
java collections
source share
2 answers

Sorry, you're out of luck: The Set was wrapped in Collections.unmodifiableCollection , which does just that: makes the collection unmodified. The only thing you can do is copy the contents into another set and work with it.

+7
source share

Your recipient explicitly returns you an UnmodifiableCollection , which is a sort wrapper around Set that prevents modification.

In other words, the API tells you: "This is my collection, please look, but don’t touch!"

If you want to change it, you must copy it to a new set. There are HashSet copy constructors for this purpose.

+4
source share

All Articles