• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

how is an iterator created?

 
Ranch Hand
Posts: 260
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How do iterator and enumerator work?Do they actually copy the the contents of the source data structure(collection that returns this enumerator/iterator) into a diffenent data structure?
 
whippersnapper
Posts: 1843
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For typical Iterator implementations take a look at the source code for AbstractList, specifically the iterator() and listIterator() methods and the private classes Itr and ListItr that they rely on.
For Enumeration, take a look at the source code for Vector, specifically the elements() method.
In both cases, the data structures aren't copied; the Iterator and Enumeration instances just hold index variable(s) that indicate the current state of the iterator/enumeration in its traversal of the list.
Although I believe these are typical implementations, I don't think iterator and enumeration implementors are under any contract to implement this way.
 
mister krabs
Posts: 13974
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You should note that every current implementation of iterator is fail-fast. That is, the iterator will throw a ConcurrentModificationException if the underlying Collection object is changed in some way.
Sun does add this to their doc:

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

 
This will take every ounce of my mental strength! All for a tiny ad:
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic