There are four ways to remove elements from Hashset.
1) Removing All Elements
The Simplest removal method, clear(),
clears all of the elements from the set:
public void clear()
While there is no return value, you may get
an UnsupportedOperationException thrown when working with read-only set.
2) Removing Single Elements
To remove a single element, you can use
remove() method
public boolean remove(Object element)
Determining whether the element is in the
set is done via the equals method of the element. If the element is present,
the element is removed from the set and true is returned. If not found, false
is returned. If a set is read only, the removing an element will throw
UnsupportedOperationException.
3) Removing Another Collection
The third way to remove element is
removeAll():
public boolean removeAll(Collection c)
The removeAll() method takes a Collection
as an argument and removes from the set all instance of each element in the
Collection passed in.The Collection passed in can be a Set or some other Collection.
For example:-
{“a”,”b”,”c”,”d”,”e”}
And the collection passed in is
{“b”,”c”,”e”}
The resulting set would be
{“a”,”d”}
removeAll() returns true if the underlying
set changed, or false or UnsupportedOperationException.
4) Retaining Another Collection
The retainAll() method works like
removeAll(),but in opposite direction:
public boolean retainAll(Collection c)
Only those elements within the collection
argument are kept in the original set. Everything else is removed. For example:-
{“a”,”b”,”c”,”d”,”e”}
And the collection passed in is
{“b”,”c”,”e”}
The resulting set would be
{“b”,”c”,”e”}
Happy Reading.
No comments:
Post a Comment