Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.UnsupportedOperationException
        at java.util.Collections$UnmodifiableCollection.remove(Collections.java:1021)

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

like image 478
simpatico Avatar asked Jul 26 '10 21:07

simpatico


People also ask

How do I remove an item from a set?

To remove an item in a set, use the remove() , or the discard() method.

How do I remove one item from a set in Python?

Method 1: Use of discard() method The built-in method, discard() in Python, removes the element from the set only if the element is present in the set. If the element is not present in the set, then no error or exception is raised and the original set is printed.

How do you remove an element from a set in C++?

set::erase() erase() function is used to remove elements from a container from the specified position or range.

How do I remove a specific item from a list?

There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.


2 Answers

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.

like image 96
Landei Avatar answered Oct 15 '22 23:10

Landei


Your getter is explicitly returning you an UnmodifiableCollection, which is a wrapper of sorts around Sets 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.

like image 32
Steven Schlansker Avatar answered Oct 15 '22 23:10

Steven Schlansker