Collections that use a hash table for storage are usually created by the Java HashSet class. As the name suggests, HashSet implements the Set interface and it also uses a hash table which is a HashMap instance. The order of the elements in HashSet is random. The null element is permitted by this class. In terms of complexity, HashSet offers constant time performance for the basic operations like add, remove, contains and size assuming the elements are properly dispersed by the function.
What is important to know about HashSet
- HashSet stores the elements by using a mechanism called hashing.
- Duplicate elements cannot exist in a HashSet.
- Null value is permitted by HashSet.
- HashSet class is non synchronized.
- HashSet’s order is not maintained by the insertion order. The elements (in this class) are inserted on the basis of their hashcode.
- In terms of search operations, HashSet is the best approach due to its constant time complexity.
- The initial default capacity of HashSet is 16, and the load factor is 0.75.
Simple diagram of HashSet structure
Every object that we put into a HashMap is first sent through a hashing algorithm. The sole purpose of this algorithm is to generate a unique number called a hash for every single object that we have passed into it. In the diagram above, this algorithm has generated number 3 for the String Lisa Morgan, the number 2 for Bob Wiliams and the number 1 for Jane Smith. Later, these numbers are stored as indices in an array. Whenever you want to do any type of operation on elements in the HashSet, you would be addressing them via this indices generated by the hashing algorithm. This is why HashSet returns elements in a random order. The hash number is the only order that HashSet knows.
Constructors in HashSet
- HashSet hashSet = new HashSet();
- HashSet hashSet = new HashSet(int initialCapacity);
- HashSet hashSet = new HashSet(int initialCapacity, float loadFactor);
- HashSet hashSet = new HashSet(Collection C);
The main difference between these constructors is that in #1 constructor, initial capacity is 16 and the default load factor is 0.75 but in #2 you can actually set the capacity. The load factor’s default value is still 0.75. In constructor #3 you can set both the capacity and the load factor.
Methods in HashSet class
- boolean add(Object o): Used to add the element provided as a parameter and if not present, return false.
- void clear(): Used to remove all elements.
- boolean contains(Object o): Returns true if the specified Object is in the HashSet and false if otherwise.
- boolean remove(Object o): Used to remove the specified Object from the HashSet (if present).
- Iterator iterator(): Used to return an iterator over the element in the set.
- boolean isEmpty(): Used to check whether the HashSet is empty or not. Returns true if it is empty and false if otherwise.
- int size(): Returns the size of the set.
- Object clone(): Creates a copy of the set.
For documentation for all the methods, you can visit the Oracle official documentation page.
Adding elements in a HashSet using add()
Syntax: HashSet.add(Object o);
import java.io.*; import java.util.HashSet; public class HashSetExample { public static void main(String args[]) { // Creating an empty HashSet HashSet<String> animals = new HashSet<String>(); animals.add("Elephant"); animals.add("Tiger"); animals.add("Lion"); // Displaying the HashSet System.out.println("HashSet: " + animals); } }
Output:
HashSet: [Elephant, Tiger, Lion]
Clearing a HashSet using clear()
Syntax: HashSet.clear();
Output:
import java.io.*; import java.util.HashSet; public class HashSetExample{ public static void main(String args[]) { // Creating an empty HashSet HashSet<String> animals = new HashSet<String>(); animals.add("Elephant"); animals.add("Tiger"); animals.add("Lion"); // Displaying the HashSet System.out.println("HashSet: " + animals); // Clearing the hash set animals.clear(); // Displaying the final Set after clearing; System.out.println("The final set: " + animals); } }
HashSet: [Elephant, Tiger, Lion] The final set: []
Checking whether an elements exists in a HashSet using contains()
Syntax: Hash_Set.contains(Object o)
import java.io.*; import java.util.HashSet; public class HashSetExample { public static void main(String args[]) { // Creating an empty HashSet HashSet<String> animals = new HashSet<String>(); animals.add("Elephant"); animals.add("Tiger"); animals.add("Lion"); // Displaying the HashSet System.out.println("HashSet: " + animals); // Checking for "Lion" in the hash set System.out.println("Does the HashSet contain 'Lion'? " + animals.contains("Lion")); // Checking for "Elephant" in the hash set System.out.println("Does the HashSet contain 'Elephant'? " + animals.contains("Elephant")); // Checking for "Tiger" in the hash set System.out.println("Does the HashSet contain 'Tiger'? " + animals.contains("Tiger")); // Checking for "Chicken" in the hash set System.out.println("Does the HashSet contain 'Chicken'? " + animals.contains("Chicken")); } }
Output:
HashSet: [Elephant, Tiger, Lion] Does the Set contain 'Lion'? true Does the Set contain 'Elephant? true Does the Set contain 'Tiger'? true Does the Set contain 'Chicken'? false
Removing an element from a HashSet using remove()
Syntax: HashSet.remove(Object o)
import java.util.*; import java.util.HashSet; public class HashSetExample { public static void main(String args[]) { // Creating an empty HashSet HashSet<String> animals = new HashSet<String>(); animals.add("Elephant"); animals.add("Tiger"); animals.add("Lion"); // Displaying the HashSet System.out.println("HashSet: " + animals); set.remove("Elephant"); set.remove("Lion"); // Displaying the HashSet after removal System.out.println("HashSet after removing elements: " + animals); } }
Output:
HashSet: [Elephant, Tiger, Lion] HashSet after removing elements: [Tiger]
Iterator() Method
Syntax: Iterator iterator = HashSet.iterator();
import java.util.*; import java.util.HashSet; public class HashSetExample { public static void main(String args[]) { // Creating an empty HashSet HashSet<String> animals = new HashSet<String>(); animals.add("Elephant"); animals.add("Tiger"); animals.add("Lion"); // Displaying the HashSet System.out.println("HashSet: " + animals); // Creating an iterator Iterator iterator = animals.iterator(); // Displaying the values after iterating through the set System.out.println("The iterator values are: "); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
Output:
HashSet: [Elephant, Tiger, Lion] The iterator values are: Elephant Tiger Lion
Checking whether a HashSet is empty or not using isEmpty()
Syntax: HashSet.isEmpty();
import java.io.*; import java.util.HashSet; public class HashSetExample { public static void main(String args[]) { // Creating an empty HashSet HashSet<String> animals = new HashSet<String>(); animals.add("Elephant"); animals.add("Tiger"); animals.add("Lion"); // Displaying the HashSet System.out.println("HashSet: " + animals); // Check for the empty set System.out.println("Is the hash set empty: " + animals.isEmpty()); set.clear(); // Checking after we've cleared it out System.out.println("Is the hash set empty: " + animals.isEmpty()); } }
Output:
HashSet: [Elephant, Tiger, Lion] Is the hash set empty: false Is the hash set empty: true
Getting the size of a HashSet using size()
Syntax: HashSet.size();
import java.util.*; import java.util.HashSet; public class HashSetExample { public static void main(String args[]) { // Creating an empty HashSet HashSet<String> animals = new HashSet<String>(); animals.add("Elephant"); animals.add("Tiger"); animals.add("Lion"); // Displaying the HashSet System.out.println("HashSet: " + animals); // Get the size of the hash set System.out.println("The size of the hash set is: " + animals.size()); } }
Output:
HashSet: [Elephant, Tiger, Lion] The size of the hash set is: 3
Cloning a HashSet using clone()
Syntax: HashSet.clone()
import java.io.*; import java.util.HashSet; public class HashSetExample { public static void main(String args[]) { // Creating an empty HashSet HashSet<String> animals = new HashSet<String>(); animals.add("Elephant"); animals.add("Tiger"); animals.add("Lion"); System.out.println("HashSet: " + animals); // Creating a new set HashSet clonedSet = new HashSet(); // Cloning the set using clone() method clonedSet = (HashSet)animals.clone(); // Displaying the new hashset; System.out.println("The new set: " + clonedSet); } }
Output:
HashSet: [Elephant, Tiger, Lion] The new set: [Elephant, Tiger, Lion]
How to iterate through HashSet
There are two ways to iterate through HashSet:
- Using iterator
- Without using iterator
1)Using an iterator
import java.util.HashSet; import java.util.Iterator; class IterateHashSetExample{ public static void main(String[] args) { HashSet<String> animals= new HashSet<String>(); //add elements to HashSet animals.add("Elephant"); animals.add("Tiger"); animals.add("Lion"); Iterator<String> iterator = animals.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } } }
The code above simply “attaches” an iterator to the animals hash set and then just prints every single one until there aren’t any more. Also as a side note, this method ignores duplicates. If there were to be a duplicate, the duplicate would be printed only once.
Output:
Elephant Tiger Lion
2)Without using an iterator
import java.util.HashSet; import java.util.Set; class IterateHashSetExample{ public static void main(String[] args) { Set<String> animals = new HashSet<String>(); //add elements to HashSet animals.add("Elephant"); animals.add("Tiger"); animals.add("Lion"); for (String animal : animals) { System.out.println(animal); } } }
Output:
Elephant Tiger Lion