Treat Enumeration as Iterator

前端 未结 7 2161
感动是毒
感动是毒 2021-01-04 02:22

I have a class that implements the Enumeration interface, but Java\'s foreach loop requires the Iterator interface. Is there an <

相关标签:
7条回答
  • 2021-01-04 03:09

    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?

    0 讨论(0)
提交回复
热议问题