HashSet In Java

HashSet stores object using Hash table. Hash table uses a mechanism hashing for storing informations.


 

Ads

Tutorials   
How to read properties file in Java? Generate random numbers in Java Cloneable Interface in Java What is the flaw with the Stack class? List In Java Java Stack Example HashSet In Java Enumeration in java How to generate random number in java Iterator in java Queue in java Transient Java Keyword clone method in Java Java Queue example Logger in Java Java current date - How to get current date in Java Collection : LinkedList Example Collection : ArrayList Example Random alpha numeric string of fixed size Java List Iterator Example The Hashtable Class The BitSet class Java Vector Java Enumeration Data Structures in Java Java Transient Variable Java Date Format Example Java Properties File Example Map.Entry Java Interface Java Property File java preferences,Change the value of Preferences by user Retrieving a Preference Node Java hasNext Write Keys and Values to the Properties file in Java Get All Keys and Values of the Properties files in Java Properties file in Java Properties file in Java Determining If a Preference Node Contains a Specific Value Change the value of Preferences by user Clone method example in Java Implementing a Simple Event Notifier Determining When a Preference Node Is Added or Removed Listening for Changes to Preference Values in a Preference Node Importing Preferences Finding a Preference in a Preference Tree Retrieving the Parent and Child Nodes of a Preference Node Determining If a Preference Node Exists Removing a Preference Node Creating a Preference Node Getting the Maximum Size of a Preference Key and Value
Ads

HashSet In Java

In this section we will read about HashSet in Java.

HashSet is a class of java.util package which extends an AbstractSet and implements the Set interface. This class is supported by the instance of HashMap. HashSet allows to insert the null element. HashSet is not thread safe i.e. in multiple threading environment a thread (at least one or more) may modify the set thus HashSet is required to be synchronized explicitly. You may use Collections.synchronizedSet( new HashSet()) method to achieve the synchronization on some objects.

Set doesn't take care of the insertion of elements in order.

Create An Object Of HashSet

Object of HashSet can be created using the following of its constructor :

HashSet hs = new HashSet();
HashSet hs1 = new HashSet(Collection c);
HashSet hs2 = new HashSet(int intialCapacity);
HashSet hs3 = new HashSet(int initialCapacity, float loadFactor);

e.g.

HashSet hs = new HashSet();
HashSet hs1 = new HashSet(Arrays.asList(?Java?,?C++?)); // HashSet from Array list.
HashSet hs2 = new HashSet(50); // HashSet with initial capacity.

Methods of HashSet

HashSet has some methods to work with the object for example, store object, remove object, check for the empty set, clear the HashSet, size of the HashSet, check for the object in the HashSet, traversing over the set element, etc.

Method Name Method Description
boolean add(E e) This method is used to add the given element into the set. This method will not add the given element if the set has already contain the specified element.
Syntax :
public boolean add(E e)
 
boolean remove(Object o) This method is used to remove the given element from the set.
Syntax :
public boolean remove(Object o)
 
boolean isEmpty() This method is used to check the set whether it is empty or not. i.e. whether it does contain at least one element or not. Returns false if the set contains at least one or more elements.
Syntax :
public boolean isEmpty()
 
void clear() This method is used to clear all the elements of a set.
Syntax :
public void clear()
 
int size() This method is used to find out the number of available elements in the set.
Syntax :
public int size()
 
boolean contains(Object o) This method is used to check out the availability of elements in the set.
Syntax :
public boolean contains(Object o)
 
Iterator iterator() This method is used to get the Iterator of Set to traverse over the elements in the set.
Syntax :
public Iterator iterator()

Example

Here I am giving a simple example which will demonstrate you about how to add elements into a set, how to remove the given elements from set, how to clear elements of a set, how to traverse over the element of set, how to check for the availability of a given object into a set, how to check the size of set, how to check the set is empty. In this example we will create a Java class and then we will create an object of HashSet and then we will first add the elements into set, then we will search for the particular object in the set, then we will get the size of the set, then we will get the iterator of set and then we will traverse over the element of set, then we will remove the given element, etc.

HashSetInJava.java


import java.util.*;
public class HashSetInJava {

	public static void main(String args[])
	{
		HashSet hs = new HashSet();
		//store object into set
		hs.add("Java");
		hs.add("C++");
		hs.add(".NET");
		hs.add("Pascal");
		//try to add duplicate element
		hs.add("Java");

		//check for whether the set is empty
		boolean empty = hs.isEmpty();
		System.out.println("set is empty : "+empty);
		
		//getting the Iterator of set and traversing over the elements of set
		Iterator itr = hs.iterator();
		System.out.println("Elements of set :");
		while(itr.hasNext())
		{
			System.out.println(itr.next());
		}
		
		//getting the size of set
		int size = hs.size();
		System.out.println("Number of elements in set : "+size);
		
		//check for the availability of the given object in set
		boolean contain = hs.contains("Java");
		System.out.println("Whether the element 'Java' is available in set : "+contain);
		
		//removing the element from set
		boolean remove = hs.remove("Pascal");
		System.out.println("Element is removed : "+remove);
		
		//Remove all elements from the set
		hs.clear();
		
		System.out.println("Set is empty : "+hs.isEmpty());		
	}
}

Output

When you will execute the above example you will get the output as follows :

Download Source Code

Advertisements

Share on Google+Share on Google+

HashSet In Java

Posted on: August 2, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: HashSet In Java  

Post your Comment


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

Ads

 

Ads