Methods in HashSet

There are different methods defined in HashSet to perform various operations

1) boolean add(Object obj)
2) void clear()
3) Object clone()
4) boolean contains(Object obj)
5) boolean isEmpty()
6) boolean remove(Object obj)

Let’s discuss each of these methods in detail

boolean add(Object obj)

It adds the element obj to the Set.

Example :

  1.  HashSet<String> hs =  new HashSet<String>();
  2.  hs.add("java");
 HashSet<String> hs =  new HashSet<String>();
 hs.add("java");


void clear()

It removes all the elements from the list.

Example :

  1. HashSet<String> hs =  new HashSet<String>();
  2. hs.add("java");
  3. hs.add(“c”);
  4. hs.clear();
HashSet<String> hs =  new HashSet<String>();
hs.add("java");
hs.add(“c”);
hs.clear();


Object clone()

This method returns a shallow copy of the HashSet.

Note : Elements will not be cloned, only HashSet is cloned


Example :

  1. HashSet<String> hs =  new HashSet<String>();
  2. hs.add("java");
  3. hs.add(“c”);
  4. HashSet clonedSet = (HashSet)hs.clone();
HashSet<String> hs =  new HashSet<String>();
hs.add("java");
hs.add(“c”);
HashSet clonedSet = (HashSet)hs.clone();


boolean contains(Object obj)

It checks whether the specified Object obj is present in the Set or not.

If the object has been found it returns true else false.

Example :

  1. HashSet<String> hs =  new HashSet<String>();
  2. hs.add("java");
  3. boolean isElementExist = hs.contains(“java”);
HashSet<String> hs =  new HashSet<String>();
hs.add("java");
boolean isElementExist = hs.contains(“java”);


boolean isEmpty()

It returns true if there is no element present in the Set.

Example :

  1. HashSet<String> hs =  new HashSet<String>();
  2. hs.add("java");
  3. boolean isEmptySet = hs.isEmpty();
HashSet<String> hs =  new HashSet<String>();
hs.add("java");
boolean isEmptySet = hs.isEmpty();


int size()

It gives the number of elements of a Set.

Example :

  1. HashSet<String> hs =  new HashSet<String>();
  2. hs.add("java");
  3. int size = hs.size();
HashSet<String> hs =  new HashSet<String>();
hs.add("java");
int size = hs.size();


boolean remove(Object obj)

It removes the specified Object obj from the Set

Example :

  1. HashSet<String> hs =  new HashSet<String>();
  2. hs.add("java");
  3. boolean isEleRemoved = hs.remove(“java”);
HashSet<String> hs =  new HashSet<String>();
hs.add("java");
boolean isEleRemoved = hs.remove(“java”);

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on