Warning: Parameter 1 to Language::getMagic() expected to be a reference, value given in /home/wikija5/public_html/w/includes/StubObject.php on line 58

Warning: Parameter 3 to renderSEO() expected to be a reference, value given in /home/wikija5/public_html/w/includes/parser/Parser.php on line 3243
Iterate through an Enumeration - WikiJava
Sunday, 14th February 2016
Follow WikiJava on twitter now. @Wikijava

Iterate through an Enumeration

From WikiJava

Jump to: navigation, search
The author suggests:

buy this book

This example shows how to Iterate through the elements of an Enumeration using the power of the Generics in Java 5


the article

Many standard implementations use the java.lang.Enumeration as a simple way to generate a collection. Unfortunately sometimes we need to iterate through these collections.

The best way to iterate through collections is of course using the java.util.Iterator. Since the java.lang.Enumeration does not implement the java.lang.Iterable interface it may be a problem to explore these elements.

The solution proposed here is to transform the java.lang.Enumeration into a java.lang.ArrayList, which instead implements java.lang.Iterable.

This is done using the static method list() from the java.util.Collections class. The method has the following signature:

public static <T> ArrayList<T> list(Enumeration<T> e)

In the example it's shown an hypothetical situation in which you need to iterate through the names of the parameters passed to a servlet from an HTTP query.

the method getParameterNames() from javax.servlet.http.HttpServletRequest has the following signature:

public java.util.Enumeration getParameterNames()

so the items returned can not be iterated directly.

Iterating through an Enumeration

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException
    List<String> requestParameterNames = Collections.list((Enumeration<String>)request.getParameterNames());
    for ( String parameterName:requestParameterNames){
        if (parameterName.equals("something")) {

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page

Comments on wikijava are disabled now, cause excessive spam.