Implement Java Iterator and Iterable in same class? -


i trying understand java iterator , iterable interfaces

i writing class

class myclass implements iterable<string> {     public string[] = null;     public myclass(string[] arr) {         = arr;         }      public myclassiterator iterator() {         return new myclassiterator(this);     }      public class myclassiterator implements iterator<string> {         private myclass myclass = null;         private int count = 0;         public myclassiterator(myclass m) {             myclass = m;             }          public boolean hasnext() {             return count < myclass.a.length;         }         public string next() {             int t = count;             count++;             return myclass.a[t];         }          public void remove() {             throw new unsupportedoperationexception();         }     }    } 

it seems working.

should have:

myclass implements iterable<stirng>, iterator<string> {  } 

or should put myclassiterator outside myclass as

class myclass implements iterable<string> {     public string[] = null;     public myclass(string[] arr) {         = arr;         }     public myclassiterator iterator() {         return new myclassiterator(this);     } }       public class myclassiterator implements iterator<string> {         private myclass myclass = null;         private int count = 0;         public myclassiterator(myclass m) {             myclass = m;             }          public boolean hasnext() {             return count < myclass.a.length;         }         public string next() {             int t = count;             count++;             return myclass.a[t];         }          public void remove() {             throw new unsupportedoperationexception();         }     }    

which 1 better?

you should never implement both iterable , iterator in same class. different things. iterator naturally stateful - iterate using it, has update view of world. iterable, however, needs able create new iterators. in particular, have several iterators working on same original iterable @ same time.

your current approach pretty okay - there aspects of implementation i'd change, it's fine in terms of separation of responsibilities.


Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -