What is HashSet in java

In following example we will discuss about HashSet in Java. The HashSet class implements the set interface. We have stored data of collection used for HashSet method.hashSet stored only object HashSet class in java.util package. The HashSet does not accept duplicate value.

What is HashSet in java

In following example we will discuss about HashSet in Java. The HashSet class implements the set interface. We have stored data of collection used for HashSet method.hashSet stored only object HashSet class in java.util package. The HashSet does not accept duplicate value.

What is HashSet in java

In following example we will discuss about HashSet in Java. The HashSet class implements the set interface. We have stored data of collection used for HashSet method.hashSet stored only object HashSet class in java.util package. The HashSet does not accept duplicate value. HashSet has many available methods like add(), remove(),size() and test the element of the collection.

The HashSet provide three constructors. Syntax of these Constructors are:-

  • HashSet( )
  • HashSet(Collection x)
  • HashSet(int capacity)

The HashSet() constructor are default value. Second constructor are initialization used by element of 'x' and last one is initializes the capacity.

The HashSet are many method are :-

add() : - The add() method is used to add elements of Set.

remove():- The remove() method is used to remove of the set and delete the specified element.

Size():-The size() method is used to get a size of set

Example :-


import java.util.HashSet;

public class HashSetExample {
	public static void main(String[] args) {
		HashSet hashSet = new HashSet();
		hashSet.add("Rohan");
		hashSet.add ("CA");
		hashSet.add ("WI");
		hashSet.add ("NY");
		hashSet.add("TC");
		hashSet.add("AB");
		hashSet.add("NDLS");
		hashSet.add("TC"); //TC is a duplicate value
	     System.out.println("HashSet is " + hashSet);
	     hashSet.remove("TC");// TC is a remove the element
	     System.out.println("HashSet after removing TC is " + hashSet);
	     int size=hashSet.size();
	     System.out.println("Size of HashSet after adding duplicate item is " + size);
	     System.out.println("Is HashSetset contains a " + hashSet);
	     System.out.println("Is HashSet contains TC " + hashSet.contains("TC"));

	}
}

OutPut :-

Download Source Code