In essence, an iterator in terms of state - it needs to know where it points in the collection. This is not part of the collection itself - and this explanation is correct ... it is entirely possible to have two independent iterator objects, iterating over the same collection object. How would you formulate this if the collection itself implemented the Iterator interface? This is possible (for example, creating a new instance of the collection, which in turn contained a link to the original collection), but it would be very ugly.
There are some problems here:
- Data collection
- The cursor located inside the collection
Separate problems => separate classes.
The easiest way to convince yourself of this is probably to try to implement your own collection - and then have multiple iterators. For example, you can try:
List<String> foo = new MyListImplementation<String>(); foo.add("a"); foo.add("b"); // The enhanced for loop uses Iterable/Iterator for non-arrays for (String x : foo) { for (String y : foo) { System.out.println(x + " " + y); } }
This should print:
aa ab ba bb
Try to implement it without having two classes, and see how you do it, given the separation of problems.
Jon skeet
source share