This class implements the Set interface, backed by a hash table (actually a HashMap instance). It does not guarantee the iteration order of the set. This means that the iteration order of Java HashSet elements doesn’t remain constant. This class permits the null element.
Points to Note about HashSet:
- HashSet internally uses Hashtable data structure.
- HashSet doesn’t maintain any order, the elements would be returned in any random order.
- HashSet doesn’t allow duplicates. If you try to add a duplicate element in HashSet, the old value would be overwritten.
- HashSet allows null values, however if you insert more than one nulls, it would override the previous null value.
- HashSet is non-synchronized. However it can be synchronized explicitly like this:
Set s = Collections.synchronizedSet(new HashSet(...));
- The iterator returned by this class is fail-fast which means iterator would throw
ConcurrentModificationException
, if HashSet has been modified after creation of iterator, by any means except iterator’s own remove method.
A Simple Example of HashSet in Java
Let’s see a simple HashSet example, where we are adding few string elements to HashSet and then iterating the HashSet to print the elements.
import java.util.HashSet; public class JavaExample { public static void main(String args[]) { // HashSet declaration HashSet<String> hSet = new HashSet<>(); // Adding elements to the HashSet hSet.add("Cricket"); hSet.add("Hockey"); hSet.add("Basketball"); System.out.println("HashSet Elements: "); // Iterating HashSet for(String s: hSet){ System.out.println(s); } } }
Output:
HashSet class Hierarchy
HashSet class extends AbstractSet class. The AbstractSet class implements Set interface, which extends Collection interface. This hierarchy can be represented as follows:
HashSet -> AbstractSet -> Set -> Collection -> Iterable
HashSet Declaration
HashSet class belongs to java.util package. The declaration of HashSet in Java is:
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable
Initial Capacity and Load Factor:
Initial capacity represents the initial data buckets allocated to HashSet, this automatically increases when HashSet gets full.
Load factor measures the load of HashSet, it represents how much the HashSet is full. A load factor of .60 means that when HashSet is 60% full, the capacity of HashSet is automatically increased.
Number of element in HashSet Load Factor Of HashSet = ---------------------------- Size of the HashSet
Constructors of Java HashSet Class
Constructor | Description |
HashSet() | It builds an empty HashSet with initial capacity of 16 and load factor of .75. Example: HashSet<String> hSet = HashSet<>(); |
HashSet(int initialCapacity) | It builds an empty HashSet with the specified initial capacity. The default load factor remains .75. |
HashSet(int initialCapacity, float loadFactor) | It builds an empty HashSet with the specified initial capacity and load factor. |
HashSet(Collection) | This doesn’t create an empty HashSet. It creates the HashSet with the elements copied from the passed Collection. |
Java HashSet Examples
Let’s see few examples of HashSet in Java.
1. Adding duplicate elements
HashSet overrides duplicate values.
import java.util.HashSet; public class HashSetExample { public static void main(String args[]) { // HashSet declaration HashSet<String> hset = new HashSet<String>(); // Adding elements to the HashSet hset.add("Apple"); hset.add("Mango"); hset.add("Grapes"); hset.add("Orange"); hset.add("Fig"); //Addition of duplicate elements hset.add("Apple"); hset.add("Mango"); //Addition of null values hset.add(null); hset.add(null); //Displaying HashSet elements System.out.println(hset); } }
Output:
[null, Mango, Grapes, Apple, Orange, Fig]
As you can see there all the duplicate values are not present in the output including the duplicate null value.
2. Removing elements
import java.util.HashSet; public class JavaExample { public static void main(String args[]) { // HashSet declaration HashSet<String> hSet = new HashSet<>(); // Adding elements to the HashSet hSet.add("AA"); hSet.add("BB"); hSet.add("CC"); hSet.add("DD"); hSet.add("EE"); //removing elements hSet.remove("EE"); hSet.remove("CC"); System.out.println("HashSet Elements: "); // Iterating HashSet for(String s: hSet){ System.out.println(s); } } }
Output:
HashSet Elements: AA BB DD
3. Adding elements from other Collection
Here, we are adding ArrayList elements to HashSet
import java.util.*; public class JavaExample { public static void main(String args[]) { //ArrayList declaration and and adding elements ArrayList<String> arrList=new ArrayList<>(); arrList.add("AA"); arrList.add("BB"); arrList.add("CC"); //copying ArrayList elements to HashSet HashSet<String> hSet=new HashSet(arrList); //adding another element to HashSet after copy hSet.add("DD"); System.out.println("HashSet elements: "); Iterator<String> it= hSet.iterator(); while(it.hasNext()) { System.out.println(it.next()); } } }
Output:
HashSet elements: AA BB CC DD
HashSet Methods:
- boolean add(Element e): It adds the element e to the list.
- void clear(): It removes all the elements from the list.
- Object clone(): This method returns a shallow copy of the HashSet.
- boolean contains(Object o): It checks whether the specified Object o is present in the list or not. If the object has been found it returns true else false.
- boolean isEmpty(): Returns true if there is no element present in the Set.
- int size(): It gives the number of elements of a Set.
- boolean(Object o): It removes the specified Object o from the Set.
Mahesh says
What is the difference between HashSet & ArrayList.
Umesh says
Array list is ordered collection and allowed duplicates where HashSet is not
Abhay Kumar Dash says
In Array List Dont follow default Sorting mechanism but In case Of Hash Set its possible and Insertion is not preserved in Hash set
So the Collection Gives Facility for default sorting by using utility class ‘Collections’
Torben says
quick and easy tutorial for java hashsets. thanks!
Marcos Lerin says
I think this point is not correct:
2.-HashSet doesn’t allow duplicates. If you try to add a duplicate element in HashSet, the old value would be overwritten.
The Java docs mention: If this set already contains the element, the call leaves the set unchanged and returns false.
RAVI PRAKASH says
Hash set can contains null value whereas array list cannot
ARNOLD says
hello
thanks for your site
i have a Question
how can
Writing program with Hashset that show me
Repetitive words ???
manish gour says
This tutorial is superb, I like it.
and It think by – “if HashSet has been modified after creation of iterator”
You mean this:
HashSet hs = new HashSet();
Song s1 = new Song(“zzz”, “zaheer”, “23”, “343”);
Song s2 = new Song(“xx”, “mosin”, “23”, “343”);
hs.add(s1);
hs.add(s2);
Iterator itr = hs.iterator();
Song s6 = new Song(“ooo”, “yakoob”, “23”, “343”);
hs.add(s6);
while (itr.hasNext()) {
System.out.println(itr.next());
}
shardul says
==================Hash List===================
[null, Apple, Grapes, Fig, Mango, Orange]
hi, I tried your code but it gets the result in sorted format.
Naja says
can equal objects be added to hashset ? if yes then why it is not considered as duplicate ?
amin says
thank you for the tutorial
but the fact that ” If you try to add a duplicate element in HashSet, the old value would be overwritten.” is not true.
according to what it says on oracle website in this link (https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html), it’s the other way around (i.e. if element_to_be_added is a duplicate, it won’t be added at all):
public boolean add(E e)
Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.