| |
Java Collections -HashSet implements Set Interface-Java Collections
import java.util.HashSet;
import java.util.Iterator;
/**
*
* @author Darur venu gopal
* This class Demonstrates ability to store values in HashSet and Retrieve.
* First Step Store some values in HashSet,
* Observe the Storage. Hashset Stores the values randomly.
* Hashset stores no duplicate values, and stores in random order.
*
*/public class HashSetDemo {
/**
* This method add values (Label number) to a hashSet.
* @return
*/
public HashSet addValuesInHashSet( ){
HashSet hashSet = new HashSet();
for( int i = 0; i< 100; i++ ){
String name = "LABEL";
String valueToAdd = name + i;
hashSet.add( valueToAdd );
}
return hashSet;
}
/**
* Iterate and hashset. and print all the values in this Hashset.
* @param hashSet
*/
public void retrieveHashSet( HashSet hashSet ){
Iterator iterator = hashSet.iterator();
while ( iterator.hasNext() ){
String labelNo=( String ) iterator.next();
System.out.println( "LabelNo: " + labelNo );
}
}
// Examine what you have done in main method.
public static void main( String [] args ){
HashSetDemo hashSetDemo = new HashSetDemo( );
HashSet hashSet = hashSetDemo.addValuesInHashSet();
hashSetDemo.retrieveHashSet(hashSet);
}
Output of the Program:
LabelNo: LABEL19
LabelNo: LABEL18
LabelNo: LABEL17
LabelNo: LABEL16
LabelNo: LABEL15
LabelNo: LABEL14
LabelNo: LABEL13
LabelNo: LABEL12
..
..
LabelNo: LABEL76
LabelNo: LABEL75
LabelNo: LABEL74
LabelNo: LABEL73
LabelNo: LABEL72
LabelNo: LABEL71
LabelNo: LABEL70
LabelNo: LABEL69
LabelNo: LABEL68
LabelNo: LABEL67
LabelNo: LABEL66
LabelNo: LABEL65
LabelNo: LABEL64
LabelNo: LABEL63
LabelNo: LABEL62
LabelNo: LABEL61
LabelNo: LABEL60
LabelNo: LABEL59
LabelNo: LABEL58
LabelNo: LABEL57
LabelNo: LABEL56
LabelNo: LABEL55
LabelNo: LABEL54
..
..
}
|