Treat Enumeration as Iterator

前端 未结 7 2160
感动是毒
感动是毒 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 02:45

    or in commons-collections EnumerationUtils

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

    toList(myEnumeration)
    
    0 讨论(0)
  • 2021-01-04 02:48

    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);
    
    0 讨论(0)
  • 2021-01-04 02:50

    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

    0 讨论(0)
  • 2021-01-04 02:57

    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).

    0 讨论(0)
  • 2021-01-04 02:58

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

    0 讨论(0)
  • 2021-01-04 03:01

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

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