Home Java Example Java Core What is HashSet in java

Related Tutorials


 
 

Share on Google+Share on Google+

What is HashSet in java

Advertisement
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.

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

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 8, 2013

Related Tutorials

Discuss: What is HashSet in java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com