Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Iterator v/s Enumeration v/s for loop

 
Viral Thakkar
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have a collection. Should I use Iterator or Enumeration or for loop to iterate through all objects of this collection ?

Regards,
Viral
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Regarding Iterator vs Enumeration: Use Iterator, which is intended as a replacement for the older Enumeration interface. Only use Enumeration when you're forced to while working with legacy code.

Regarding Iterator vs looping with "get(i)" on a list: there are many considerations; it depends on the type of container, where you're using it, how you're using it, whether clarity or performance matters more, etc. My recommendation, in general, is to use Iterator, but if you find after profiling your code that a tiny little bit of increased performance would help, then you can try looping with "get()".
[ July 13, 2004: Message edited by: Ernest Friedman-Hill ]
 
Kris Philippaerts
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Java Docs state:
NOTE: The functionality of this interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation, and has shorter method names. New implementations should consider using Iterator in preference to Enumeration.
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Viral Thakkar:
I have a collection. Should I use Iterator or Enumeration or for loop to iterate through all objects of this collection ?
Your very question tells me that you do not simply have a Collection, or any of the other interfaces from the Collections framework. You have something like a Vector or Hashtable.
  • Code to interface (List), not to implementation (Vector). That way you couple more loosely and flexibly. For example, you can simply plug in another implementation (eg LinkedList, Arrays.asList(), etc) if your chose implementation is suboptimal.
  • Choose classes from the Collections framework, such as ArrayList, HashMap and Iterator, in preference to the legacy JDK 1.1 classes, such as Vector, Hashtable and Enumeration. The legacy classes have a bloated API, do not sit as comfortably in the framework, and have generally useless synchronization.
  • - Peter
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic