Hashset

A hashset represents a set of elements. It does not guarantee the order of elements and also it does not allow the duplicate elements to be stored.

Features of Hashset

Following are the notable features of Hashset

  • Implements Set Interface.

  • The underlying data structure for HashSet is Hashtable.

  • As it implements the Set Interface, duplicate values are not allowed.

  • Objects that you insert in HashSet are not guaranteed to be inserted in the same order. Objects are inserted based on their hash code.

  • null elements are allowed in HashSet.

  • HashSet also implements Serializable and Cloneable interfaces.

Initial Capacity

The initial capacity means the number of buckets when hashtable (HashSet internally uses hashtable data structure) is created. The number of buckets will be automatically increased if the current size gets full.

Load Factor

  • The load factor is a measure of how full the HashSet is allowed to get before its capacity is automatically increased.

  • When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

                (Number of stored elements in the table)
Load Factor = -------------------------------------------
                    (Size of the hash table)

Effect on performance

  • Load factor and initial capacity are two main factors that affect the performance of HashSet operations.

  • A load factor of 0.75 provides very effective performance with respect to time and space complexity.

  • If we increase the load factor value more than that then memory overhead will be reduced (because it will decrease internal rebuilding operation) but, it will affect the add and search operation in the hashtable.

  • To reduce the rehashing operation we should choose initial capacity wisely. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operation will ever occur.

Syntax for declaration of hashset

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable

Constructors

  • HashSet(): This constructor is used to build an empty HashSet object in which the default initial capacity is 16 and the default load factor is 0.75. If we wish to create an empty HashSet with the name hs, then, it can be created as:
HashSet<E> hs = new HashSet<E>();
  • HashSet(int initialCapacity): This constructor is used to build an empty HashSet object in which the initialCapacity is specified at the time of object creation. Here, the default loadFactor remains 0.75.
HashSet<E> hs = new HashSet<E>(int initialCapacity);
  • HashSet(int initialCapacity, float loadFactor): This constructor is used to build an empty HashSet object in which the initialCapacity and loadFactor are specified at the time of object creation.
HashSet<E> hs = new HashSet<E>(int initialCapacity, float loadFactor);
  • HashSet(Collection): This constructor is used to build a HashSet object containing all the elements from the given collection. In short, this constructor is used when any conversion is needed from any Collection object to the HashSet object. If we wish to create a HashSet with the name hs, it can be created as:
HashSet<E> hs = new HashSet<E>(Collection C);

Methods in Hashset

METHODDESCRIPTION
add(E e)Used to add the specified element if it is not present, if it is present then return false
clear()Used to remove all the elements from set.
contains(Object o)Used to return true if an element is present in set.
remove(Object o)Used to remove the element if it is present in set.
iterator()Used to return an iterator over the element in the set.
isEmpty()Used to check whether the set is empty or not. Returns true for empty and false for a non-empty condition for set
size()Used to return the size of the set.
clone()Used to create a shallow copy of the set.
equals()Used to verify the equality of an Object with a HashSet and compare them. The list returns true only if both HashSet contains same elements, irrespective of order
hashcode()Returns the hash code value for this set
removeAll(collection)This method is used to remove all the elements from the collection which are present in the set. This method returns true if this set changed as a result of the call.

Operations on Hashset

Adding Elements

In order to add an element to the HashSet, we can use the add() method. However, the insertion order is not retained in the HashSet. We need to keep a note that duplicate elements are not allowed and all the duplicate elements are ignored.

// Java program to Adding Elements to HashSet

// Importing required classes
import java.io.*;
import java.util.*;

// Main class
// AddingElementsToHashSet
class TFT {

	// Method 1
	// Main driver method
	public static void main(String[] args)
	{
		// Creating an empty HashSet of string entities
		HashSet<String> hs = new HashSet<String>();

		// Adding elements using add() method
		hs.add("Tit");
		hs.add("For");
		hs.add("Tat");

		// Printing all string el=ntries inside the Set
		System.out.println("HashSet elements : " + hs);
	}
}

Output

HashSet elements : [Tit, For, Tat]

Removing Elements

The values can be removed from the HashSet using the remove() method.

// Java program Illustrating Removal Of Elements of HashSet

// Importing required classes
import java.io.*;
import java.util.*;

// Main class
// RemoveElementsOfHashSet
class TFT {

	// Main driver method
	public static void main(String[] args)
	{
		// Creating an
		HashSet<String> hs = new HashSet<String>();

		// Adding elements to above Set
		// using add() method
		hs.add("Tit");
		hs.add("For");
		hs.add("Tat");
		hs.add("A");
		hs.add("B");
		hs.add("Z");

		// Printing the elements of HashSet elements
		System.out.println("Initial HashSet " + hs);

		// Removing the element B
		hs.remove("B");

		// Printing the updated HashSet elements
		System.out.println("After removing element " + hs);

		// Returns false if the element is not present
		System.out.println("Element AC exists in the Set : "
						+ hs.remove("AC"));
	}
}

Output

Initial HashSet [A, B, Tit, For, Tat, Z]
After removing element [A, Tit, For, Tat, Z]
Element AC exists in the Set : false

Iterating through the HashSet

Iterate through the elements of HashSet using the iterator() method. Also, the most famous one is to use the enhanced for loop.

// Java Program to Illustrate Iteration Over HashSet

// Importing required classes
import java.io.*;
import java.util.*;

// Main class
// IterateTheHashSet
class TFT {

	// Main driver method
	public static void main(String[] args)
	{

		// Creating an empty HashSet of string entries
		HashSet<String> hs = new HashSet<String>();

		// Adding elements to above Set
		// using add() method
		hs.add("Tit");
		hs.add("For");
		hs.add("Tat");
		hs.add("A");
		hs.add("B");
		hs.add("Z");

		// Iterating though the HashSet using iterators
		Iterator itr = hs.iterator();

		// Holds true till there is single element
		// remaining in Set
		while (itr.hasNext())

			// Traversing elements and printing them
			System.out.print(itr.next() + ", ");
		System.out.println();

		// Using enhanced for loop for traversal
		for (String s : hs)

			// Traversing elements and printing them
			System.out.print(s + ", ");
		System.out.println();
	}
}

Output:

A, B, Tit, For, Tat, Z, 
A, B, Tit, For, Tat, Z, 

Subscribe For More Content