Get Enumeration over Java HashSet
The HashSet class implements the Set interface, backed by a hash table which is a HashMap instance. There is no assurance as to the iteration order of the set, which implies that over time, the class does not guarantee the constant order of elements. The null element is allowed by this class. The java.util.Collections class enumeration method is used to return an enumeration of the specified collection.
To return enumeration over HashSet:
Syntax:
public static Enumeration enumeration(Collection c)
Method Used: hasMoreElements() Method.
An object that implements the Enumeration interface creates one at a time, a set of objects. hasMoreElements() method of enumeration used to tests if this enumeration contains more elements. If enumeration contains more elements, then it will return true else false.
Syntax:
boolean hasMoreElements()
Return value: This method returns true if there is at least one additional element to be given in this enumeration object, otherwise return false.
Below is the full implementation of the above approach:
Java
import java.util.*;
import java.util.Enumeration;
public class GFG {
public static void main(String[] args)
{
HashSet<String> name = new HashSet<>();
name.add( "Nikhil" );
name.add( "Akshay" );
name.add( "Bina" );
name.add( "Chintu" );
name.add( "Dhruv" );
Enumeration e = Collections.enumeration(name);
while (e.hasMoreElements())
System.out.println(e.nextElement());
}
}
|
Output
Dhruv
Akshay
Chintu
Bina
Nikhil
Example 2:
Java
import java.util.*;
import java.util.Enumeration;
public class GFG {
public static void main(String[] args)
{
HashSet<String> gfg = new HashSet<>();
gfg.add( "Welcome" );
gfg.add( "On" );
gfg.add( "GFG" );
Enumeration e = Collections.enumeration(gfg);
while (e.hasMoreElements())
System.out.println(e.nextElement());
}
}
|
Last Updated :
03 Mar, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...