Rajinder Menu

In how many ways Set elements can be traversed (Non-Generic).


Following example shows how to traverse elements of a Set.

Elements of a Set can be traversed mainly in two ways:

1) Using For-Each Loop
2) Using Iterator.

In this example we are using non-generic version of Set. Generic version of this example is given here.
Note that here both in for loop and iterator loop we needed casting.
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;

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

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

Integer[] intArray = new Integer[5];

intArray[0]= new Integer(1);
intArray[1]= new Integer(2);
intArray[2]= new Integer(3);
intArray[3]= new Integer(4);
intArray[4]= new Integer(5);

/*Adding Elements*/
hs.add(intArray[0]);
hs.add(intArray[1]);
hs.add(intArray[2]);
hs.add(intArray[3]);
hs.add(intArray[4]);

int sum=0;

/*Accessing Set elements using For-Each method*/
for(Object o:hs){
/* sum = sum + o; will give error*/
sum = sum + ((Integer)o).intValue();
System.out.println((Integer)o);
}

System.out.println("Sum="+sum);

Integer intVal;
/*Accessing Set elements using 'iterator' provided by Set*/
Iterator iter = hs.iterator();
while(iter.hasNext()){
/*intVal=iter.next(); without casting it will give error.*/
intVal=(Integer)iter.next();
System.out.println(intVal);
}
}
}

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