Iterate through an EnumerationFrom WikiJavabuy this book
the articleMany 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 Enumerationpublic 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")) { dosomething(); } }
|
