为什么我不能这样做:
Enumeration e = ...
for (Object o : e)
...
发布于 2014-03-02 23:33:52
使用Collections实用程序类,可以迭代枚举,如下所示:
Enumeration headerValues=request.getHeaders("mycustomheader");
List headerValuesList=Collections.list(headerValues);
for(Object headerValueObj:headerValuesList){
... do whatever you want to do with headerValueObj
}
发布于 2013-07-31 10:31:49
我已经用两个非常简单的类解决了这个问题,一个用于Enumeration
,另一个用于Iterator
。枚举封装器如下:
static class IterableEnumeration<T>
extends Object
implements Iterable<T>, Iterator<T>
{
private final Enumeration<T> enumeration;
private boolean used=false;
IterableEnumeration(final Enumeration<T> enm) {
enumeration=enm;
}
public Iterator<T> 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<T>` to an `Iterable<T>` for a once-off use in an enhanced for loop.
*/
static public <T> Iterable<T> asIterable(final Enumeration<T> enm) {
return new IterableEnumeration<T>(enm);
}
...
for(String val: Util.asIterable(enm)) {
...
}
或者通过实例化该类:
for(String val: new IterableEnumeration<String>(enm)) {
...
}
发布于 2009-08-06 16:39:04
新风格的for-loop ("foreach")适用于数组和实现Iterable
接口的东西。
它也更类似于Iterator
,而不是Iterable
,所以对于Enumeration
来说,使用foreach是没有意义的,除非Iterator
也这样做了(但它并没有)。支持Iterator
的人也不鼓励使用Enumeration
。
https://stackoverflow.com/questions/1240077
复制相似问题