java 不能使用foreach_为什么我不能在Java Enumeration上使用foreach?
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)) {
...
}
總結
以上是生活随笔為你收集整理的java 不能使用foreach_为什么我不能在Java Enumeration上使用foreach?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 上海沃尔沃小轿车后玻璃雨刷器自动打开停不
- 下一篇: 130货车怎么放刹车水?