Lawrence Dol..
6
我用两个非常简单的类解决了这个问题,一个用于Enumeration,一个用于Iterator.枚举包装如下:
static class IterableEnumeration
extends Object
implements Iterable, Iterator
{
private final Enumeration enumeration;
private boolean used=false;
IterableEnumeration(final Enumeration enm) {
enumeration=enm;
}
public Iterator iterator() {
if(used) { throw new IllegalStateException("Cannot use iterator from asIterable wrapper more than once"); }
used=true;
return this;
}
public boolean hasNext() { return enumeration.hasMoreElements(); }
public T next() { return enumeration.nextElement(); }
public void remove() { throw new UnsupportedOperationException("Cannot remove elements from AsIterator wrapper around Enumeration"); }
}
哪个可以使用静态实用程序方法(这是我的偏好):
/**
* Convert an `Enumeration` to an `Iterable` for a once-off use in an enhanced for loop.
*/
static public Iterable asIterable(final Enumeration enm) {
return new IterableEnumeration(enm);
}
...
for(String val: Util.asIterable(enm)) {
...
}
或者通过实例化类:
for(String val: new IterableEnumeration(enm)) {
...
}