In how many ways Set elements can be traversed.(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 generic version of Set. Non-Generic version of this example is given here.

Note that unlike non-generic version here in for loop and iterator loop we did not need 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<Integer> hs = new HashSet<Integer>();

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(Integer i:hs){
sum = sum + i.intValue();
System.out.println(i.intValue());
}

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

Integer intVal;

/*Accessing Set elements using 'iterator'*/
Iterator<Integer> iter = hs.iterator();  /*Note the use of generic iterator*/

while(iter.hasNext()){
intVal=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