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?

inner class inner class

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

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -