How to use HashSet(Non-Generic).


HashSet is an implmentation 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*/
s.add("A");
s.add("B");
s.add("C");
s.add("D");

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

if(s.contains("E"))
System.out.println(" HashSet contains E");
else
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);
s.clear();
b= s.isEmpty();
System.out.println(" Set Empty? :"+b);

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

Output:


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