Treat Enumeration<T> as Iterator<T>

我的未来我决定 提交于 2019-11-30 01:47:05

问题


I have a class that implements the Enumeration<T> interface, but Java's foreach loop requires the Iterator<T> interface. Is there an Enumeration to Iterator Adapter in Java's standard library?


回答1:


You need a so called "Adapter", to adapt the Enumeration to the otherwise incompatible Iterator. Apache commons-collections has EnumerationIterator. The usage is:

Iterator iterator = new EnumerationIterator(enumeration);



回答2:


If you just want something to iterate over in a for-each loop (so an Iterable and not only an Iterator), there's always java.util.Collections.list(Enumeration<T> e) (without using any external libraries).




回答3:


a) I'm pretty sure you mean Enumeration, not Enumerator
b) Guava provides a Helper method Iterators.forEnumeration(enumeration) that generates an iterator from an Enumeration, but that won't help you either, as you need an Iterable (a provider of Iterators), not an Iterator
c) you could do it with this helper class:

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;
    }
}

And now your client code would look like this:

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

But is that worth the effort?




回答4:


No need to roll your own. Look at Google's Guava library. Specifically

Iterators.forEnumeration()



回答5:


There's nothing that is part of the standard library. Unfortunately you'll have to roll your own adapter. There are examples out there of what others have done, for example:

IterableEnumerator




回答6:


or in commons-collections EnumerationUtils

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

toList(myEnumeration)



回答7:


If you can modify the class then you can simply implement Iterator<T> too and add the remove method..



来源:https://stackoverflow.com/questions/5007082/treat-enumerationt-as-iteratort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!