dsa

Java HashSet

In this tutorial, we will learn about the Java HashSet class. We will learn about different hash set methods and operations with the help of examples.

The HashSet class of the Java Collections framework provides the functionalities of the hash table data structure.

Hashset class which is implemented in the collection framework is an inherent implementation of the hash table datastructure. The objects that we insert into the hashset does not guarantee to be inserted in the same order. The objects are inserted based on their hashcode. This class also allows the insertion of NULL elements. Let’s see how to create a set object using this class.

hashset

Example:

// Java program to demonstrate the 
// creation of Set object using 
// the Hashset class 
import java.util.*; 

class Codmistic
{ 
	public static void main(String[] args) 
	{ 
		Set<String> h = new HashSet<String>(); 

		// Adding elements into the HashSet 
		// using add() 
		h.add("India"); 
		h.add("Australia"); 
		h.add("South Africa"); 

		// Adding the duplicate 
		// element 
		h.add("India"); 

		// Displaying the HashSet 
		System.out.println(h); 

		// Removing items from HashSet 
		// using remove() 
		h.remove("Australia"); 
		System.out.println("Set after removing "
						+ "Australia:" + h); 

		// Iterating over hash set items 
		System.out.println("Iterating over set:"); 
		Iterator<String> i = h.iterator(); 
		while (i.hasNext()) 
			System.out.println(i.next()); 
	} 
} 

output:
[South Africa, Australia, India]
Set after removing Australia:[South Africa, India]
Iterating over set:
South Africa
India

Few important features of HashSet are:

Methods in Java HashSet

Sr.No. Method & Description
1

boolean add(Object o)

Adds the specified element to this set if it is not already present.

2

void clear()

Removes all of the elements from this set.

3

Object clone()

Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.

4

boolean contains(Object o)

Returns true if this set contains the specified element.

5

boolean isEmpty()

Returns true if this set contains no elements.

6

Iterator iterator()

Returns an iterator over the elements in this set.

7

boolean remove(Object o)

Removes the specified element from this set if it is present.

8

int size()

Returns the number of elements in this set (its cardinality).