How to Browse a HashSet in Java
Java offers 3 ways to navigate through HashSet in Java:
- Foreach Loop
- While loop with Iterator
- While loop with java.util.Enumeration
The following example gathers the 3 cases without Iterator or with Iterator and prints the results:
The interface java.util.Enumeration returns an object that generates a series of elements and uses two methods: hasMoreElements() to check if there are any more elements, if so, it retrieves the following element with the method nextElement().
References:
java.util.HashSet.iterator() Method
JavaDoc: Enumeration Interface< E>
import java.util.Collections;Let's see what happens by running this program:
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
public class parcours_hashset {
public static void main(String[] args) {
HashSet< String> hset = new HashSet< String> ();
hset.add("he1");
hset.add("he2");
hset.add("he3");
/*Advanced For Loop*/
System.out.println("Advanced For Loop");
for(String s: hset)
System.out.println(s);
/*While+Iterator Loop*/
System.out.println("While+Iterator Loop");
Iteratorit = hset.iterator();
while(it.hasNext())
System.out.println(it.next());
/*Enumeration*/
System.out.println("While+Enumeration Loop");
// retrieve the Enumeration
Enumerationenumeration = Collections.enumeration(hset);
// read through HashSet
while(enumeration.hasMoreElements())
System.out.println(enumeration.nextElement());
}
}
Loop for advancedThe iterator() is used to get an iterator through the elements of the HashSet or Set. Elements are returned mixed and without any specific order.
he3
he1
he2
While+Iterator
he3
he1< br />he2
While+Enumeration Loop
he3
he1
he2
The interface java.util.Enumeration returns an object that generates a series of elements and uses two methods: hasMoreElements() to check if there are any more elements, if so, it retrieves the following element with the method nextElement().
References:
java.util.HashSet.iterator() Method
JavaDoc: Enumeration Interface< E>