Learn HashSet Class in Java with Programming Example

hashsetIn this chapter you will learn:

  1. What is HashSet Class in Java?
  2. Declaration and Methods of HashSet Class
  3. Programming Example
What is HashSet class in Java?

The HashSet Class implements the Set interface and stored items into a hash table. Iteration order might be different from insertion order. That means it takes no guarantee of element’s order as they inserted or no guarantee of same order result in each iteration. Some Fact about HashSet Class:

  1. It stores data in a Hash Table.
  2. Orders of elements are not guaranteed and you may get different order result in each iteration.
  3. It allows null elements.
  4. HashSet is not synchronized so if multiple threads are accessing this and one thread makes changes then you must synchronize HashSet Externally.


HashSet()Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).
HashSet(Collection<? extends E> c)Constructs a new set containing the elements in the specified collection.
HashSet(int initialCapacity)Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default load factor (0.75).
HashSet(int initialCapacity, float loadFactor)Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the specified load factor.


boolean add(E e)Adds the specified element to this set if it is not already present.
void clear()Removes all of the elements from this set.
Object clone()Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
boolean contains(Object o)Returns true if this set contains the specified element.
boolean isEmpty()Returns true if this set contains no elements.
Iterator<E> iterator()Returns an iterator over the elements in this set.
boolean remove(Object o)Removes the specified element from this set if it is present.
int size()Returns the number of elements in this set (its cardinality).


Methods Inherited From Class

java.util.AbstractSetequals(), hashCode(), removeAll()
java.util.AbstractCollectionaddAll(), containsAll(), retainAll(), toArray(), toArray(), toString()
java.lang.Objectfinalize(), getClass(), notify(), notifyAll(), wait(), wait(), wait()
java.util.SetaddAll(), containsAll(), equals(), hashCode(), removeAll(), retainAll(), toArray(), toArray()


Programming Example


D:\JavaProgram>javac HashSet_Example.java
D:\JavaProgram>java HashSet_ExampleSQL C# PHP HTML Java
Item Removed : true


In this chapter you have learned HashSet Class in Java with complete programming example. In the next chapter you will learn about LinkedHashSet Class.

Leave a Reply

Your email address will not be published. Required fields are marked *