Code Pretty Print Script

Saturday, November 9, 2013

That API returns an Enumeration, but I wanted an Iterator!

You're working on a Servlet, and you need to iterate the parameter names but "getRequestParameterNames()" returns an Enumeration. You could use hasMoreElements and nextElement but it's completely inconsistent with your other (modern) Collections. There has to be an easier way!
/*
 * Copyright © 2013 - Elliott Frisch
 * 
 * THIS SOFTWARE IS PROVIDED UNDER THE CREATIVE COMMONS
 * LICENSE 3.0 "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR
 * A PARTICULAR PURPOSE.
 * 
 * To use this software you must agree to the complete
 * license terms available at:
 * http://creativecommons.org/licenses/by/3.0/us/deed.en_US
 * 
 * It is the intent of the author(s) that you may use or
 * modify this software for any purpose (including your own
 * commercial gain) provided that this notice remains in its
 * entirety.
 * 
 * Created by Elliott Frisch - www.frischcode.com
 */
package com.frischcode.util;

import java.util.Enumeration;
import java.util.Iterator;

/**
 * <b>Rationale:</b> Frequently you have an Enumeration and
 * you'd really rather be consistent with modern code
 * practices and use an Iterator.<br/>
 * 
 * <b>Common Use Cases:</b>
 * <ul>
 * <li>HttpServletRequest.getParameterNames()</li>
 * <li>HttpServletRequest.getHeaderNames()</li>
 * <li>java.util.StringTokenizer</li>
 * </ul>
 * 
 * <b>NOTE:</b> remove() is not implemented and throws
 * NoSuchMethodError.
 * 
 * @author Elliott Frisch
 */
public class EnumerationIterator<T> implements
    Iterator<T> {

  public EnumerationIterator(
      final Enumeration<T> enumeration) {
    this.enumeration = enumeration;
  }

  private final Enumeration<T> enumeration;

  /**
   * @see java.util.Iterator#hasNext()
   */
  @Override
  public boolean hasNext() {
    return (enumeration != null && enumeration
        .hasMoreElements());
  }

  /**
   * @see java.util.Iterator#next()
   */
  @Override
  public T next() {
    return (enumeration != null) ? enumeration
        .nextElement() : null;
  }

  /**
   * <b>NOTE:</b> Throws <b>NoSuchMethodError</b> because
   * remove is <u>not implemented</u>.
   */
  @Override
  public void remove() {
    throw new NoSuchMethodError(
        EnumerationIterator.class.getName()
            + " does not implement remove.");
  }
}