2011-02-15 91 views
13

我有一個類實現了Enumeration<T>接口,但Java的foreach循環需要Iterator<T>接口。 Java標準庫中是否有EnumerationIterator適配器?將枚舉<T>作爲迭代器使用<T>

+0

它更簡單一些,不使用枚舉器作爲其遺留類或不使用每個循環的「增強」。 – 2011-02-15 17:40:51

+4

for-each循環需要Iterable,而不是Iterator;你真的想要哪個? – 2012-04-10 21:22:21

回答

9

你需要一個所謂的「適配器」,以使Enumeration適應不兼容的Iterator。 Apache公共收藏有EnumerationIterator。用法:

Iterator iterator = new EnumerationIterator(enumeration); 
+0

+1 Apache Commons – vz0 2011-02-15 17:38:23

+1

這回答了這個問題,因爲您不能在foreach循環中使用迭代器。 – 2013-01-18 14:37:52

2

沒有什麼是標準庫的一部分。不幸的是,你將不得不推出自己的適配器。有例子在那裏別人怎麼做了,例如:

IterableEnumerator

+0

是的,標準庫中有一些專門用於此目的的東西:Collections.list – aeropapa17 2016-05-02 17:12:24

0

如果你可以修改類,那麼你可以簡單地實現Iterator<T>過,並添加remove方法..

7

一)我敢肯定你的意思Enumeration,不Enumerator
B)Guava提供了一個輔助方法Iterators.forEnumeration(enumeration)產生從枚舉迭代器,但不會幫助你要麼,因爲你需要一個Iterable(一個迭代器的供應商),而不是一個Iterator
c)您可以這個助手類做到這一點:

public class WrappingIterable<E> implements Iterable<E>{ 
    private Iterator<E> iterator; 

    public WrappingIterable(Iterator<E> iterator){ 
     this.iterator = iterator; 
    } 

    @Override 
    public Iterator<E> iterator(){ 
     return iterator; 
    } 
} 

現在你的客戶端代碼應該是這樣的:

for(String string : new WrappingIterable<String>(
         Iterators.forEnumeration(myEnumeration))){ 
    // your code here    
} 

但是這是值得的?

+0

你可以讓你的包裝構造函數接受一個枚舉。 – 2012-04-10 19:07:13

3

沒有必要推出自己的。看看Google的Guava圖書館。具體

Iterators.forEnumeration() 
1

或公共的集合 EnumerationUtils

import static org.apache.commons.collections.EnumerationUtils.toList

toList(myEnumeration) 
27

如果你只是想要的東西在一個for-each循環(所以一個可迭代遍歷並不僅是一個迭代器),there's alwaysjava.util.Collections.list(Enumeration<T> e)(不使用任何外部庫)。