Why java Iterator interface should be implemented as inner class? -
i read book "the java tutorials" 3rd edition. talks inner class implementation picture shows.
in 3rd paragraph, says "the stack class should not implement iterator interface, because...".
i cannot find reason stack class should not implement iterator. reason given not persvasive.
could explain it?

fundamentally, iterator stateful - needs know where it's pointing within collection. doesn't belong part of collection - , explanation given right one... it's entirely possible have 2 independent iterator objects, iterating on same collection object. how model if collection implemented iterator interface? it's possible (e.g. creating new instance of collection in turn held reference original collection), ugly.
there separate concerns here:
- the collection of data
- a cursor positioned within collection
separate concerns => separate classes.
the simplest way of persuading of try implement own collection though - , have multiple iterators. example, might want try:
list<string> foo = new mylistimplementation<string>(); foo.add("a"); foo.add("b"); // enhanced loop uses iterable/iterator non-arrays (string x : foo) { (string y : foo) { system.out.println(x + " " + y); } } that should print out:
a a b b b b try implementing without having 2 classes, , see how do, bearing separation of concerns in mind.
Comments
Post a Comment