Tuesday, August 10, 2004

Supporting old code

One JDK5 feature I particularly appreciate is the simplicity of the new foreach syntax, and the addition of an Iterable<T> interface in support. However, much of the JDK was written before even Iterator was around such as StringTokenizer. What to do? Write a wrapper, of course:

/**
 * <code>EnumerationIterator</code> is an {@link Iterator} wrapper for {@link
 * Enumeration}. {@link #remove()} is unsupported.
 */
public class EnumerationIterator <T> implements Iterator<T> {
    private final Enumeration<T> enumeration;

    /**
     * Constructs a new <code>EnumerationIterator</code> from the given
     * <var>enumeration</var>.
     *
     * @param enumeration the enumeration
     */
    public EnumerationIterator(final Enumeration<T> enumeration) {
        this.enumeration = enumeration;
    }

    /**
     * {@inheritDoc}
     */
    public boolean hasNext() {
        return enumeration.hasMoreElements();
    }

    /**
     * {@inheritDoc}
     */
    public T next() {
        return enumeration.nextElement();
    }

    /**
     * {@inheritDoc}
     */
    public void remove() {
        throw new UnsupportedOperationException();
    }
}

/**
 * <code>EnumerationIterable</code> is an {@link Iterable} wrapper for {@link
 * Enumeration} to support JDK5 <em>foreach</em> syntax.
 */
public class EnumerationIterable <T> implements Iterable<T> {
    private final Enumeration enumeration;

    /**
     * Constructs a new <code>EnumerationIterable</code> for the given
     * <var>enumeration</var>.
     *
     * @param enumeration the enumeration
     */
    public EnumerationIterable(final Enumeration enumeration) {
        this.enumeration = enumeration;
    }

    /**
     * {@inheritDoc}
     */
    public Iterator<T> iterator() {
        return new EnumerationIterator<T>(enumeration);
    }
}

Now I can write this:

for (final String token : new EnumerationIterable<String>(new StringTokenizer("a:b:c", ":")))
    System.out.printnln(token);

1 comment:

Anonymous said...

There is an even easier way I believe.

for (final String token : Collections.list(new StringTokenizer("a:b:c", ":")).iterator()) {
System.out.printnln(token);
}