5 Replies Latest reply: Dec 1, 2010 11:08 PM by 594440 RSS

    Iterator vs Enumeration

    594440
      When we compare Iterator and Enumeration , both are a form of traversing mechanism on collections. We say that Iterator has iterate has remove() and enumeration is just read only, also Iterator can traverse bi directionally using List Iterator whereas Enumeration can only traverse in forward direction.

      but my question is when we have iterator with all facilities , why we need to have Enumerator which is only used just for read only ?

      and what is the specific reason for which the enumeration cannot be used for traversing through HashMaps ?


      please reply in detail for both the questions .
      Thanks in advance.

      balaji.k
        • 1. Re: Iterator vs Enumeration
          EJP
          but my question is when we have iterator with all facilities , why we need to have Enumerator which is only used just for read only ?
          Enumeration+ came first, and Iterator was added with the collection classes in 1.2. The basic reasons are given in the Javadoc for Iterator.
          and what is the specific reason for which the enumeration cannot be used for traversing through HashMaps?
          You can't iterate the map either. You can iterate through the entrySet(), or the keySet(), or the values(). You can't enumerate those because they are part of the Collections API that was introduced in 1.2 and they weren't retrofitted to use Enumeration; Iterator being clearly considered to have superceded it.
          please reply in detail for both the questions.
          Both these questions are answered in all available detail by the Javadoc. No further details are available unless you can find the designers of the Collections API.
          • 2. Re: Iterator vs Enumeration
            802316
            As EJP has stated, Enumeration came first and Iterator replaced it with Java 1.2 (in 1988). It and the collections which use it like Vector and Hashtable, only exists today for backward compatibility.
            This is part of the reason the enhanced for loop doesn't support Enumerations.

            In short, only use Enumerations if you have to, otherwise use Iterator.
            • 3. Re: Iterator vs Enumeration
              594440
              Thanks pater lawrey
              • 4. Re: Iterator vs Enumeration
                594440
                Thanks for the answer in detail
                • 5. Re: Iterator vs Enumeration
                  594440
                  Thanks EJP for the answer in detail ..