How to use Hashset (Generic).

HashSet is an implementation of Set interface of Java Collections Framework.

Characteristics of HashSet:

1) It does not guarantee any order of its elements when get iterated.

2) It permits null to be one of its elements.

3) It is not synchronized. It is not safe to use HashSet object in multithreaded environment without using proper synchronization.

From Java5 onwards HashSet has been made generic.

Following example shows  how to do basic operations on a HashSet object. In this example we are using non-generic form of HashSet.

import java.util.Set;
import java.util.HashSet;

public class HashSetExample{
public static void main(String args[]){

/*Creating HashSet*/
Set s = new HashSet();

/*Adding Elements*/

/*Following line will give error as this HashSet can only accept elements of type String*/
//s.add(new Integer(1));  /*Error*/

/*Checking if HashSet contains this element*/
System.out.println("HashSet contains C");
System.out.println("HashSet does NOT contains C");

System.out.println(" HashSet contains E");
System.out.println("HashSet does NOT contains E");

/*Obtaining size of HashSet*/
int setSize= s.size();
System.out.println("Size  of Set:"+setSize);

/*Removing element from HashSet*/
boolean b = s.remove("A");
System.out.println("Removed A ?:"+b);
b = s.remove("F");
System.out.println("Removed F?:"+b+ "  (Already F is Not in the set)");

/*Checking size again after removing*/
setSize= s.size();
System.out.println("Size  After removing :"+setSize);

/*Making HashSet Empty*/
b= s.isEmpty();
System.out.println(" Set Empty? :"+b);
b= s.isEmpty();
System.out.println(" Set Empty? :"+b);

/*Checking again the size*/
setSize= s.size();
System.out.println(" Size  After Clearing :"+setSize);


HashSet contains C
HashSet does NOT contains E
Size  of Set:4
Removed A ?:true
Removed F?:false  (Already F is Not in the set)
Size  After removing :3
 Set Empty? :false
 Set Empty? :true
 Size  After Clearing :0

I would like to know your comments and if you liked the article then please share it on social networking buttons.

No comments:

Post a Comment