Java - Using iterators with arrays -


i new whole "iterator" concept in java , need implementing in code. here code:

class iteratorexample {  int tstarray [];  iteratorexample(){  }  public void addnum(int num){     tstarray[0] = num; //and yes, can add 1 number @ moment,                       not want focus on right now. }   public iterator<integer> inneriterator(){     return new methoditerator(); }   class methoditerator implements iterator<integer> {     public int index;     private methoditerator(){         index = 0;     }      public boolean hasnext(){         return index < tstarray.length;      }     public integer next(){         return;     }     }      public static void main(string[] args){     iteratorexample sample = new iteratorexample();   test(sample); }  public static void test(iteratorexample arr){  arr.addnum(1);  system.out.print(arr); }  } 

this code written far. want make can add number array using addnum() method , display main using system.print (and yes, aware need tostring method in order numbers come instead of memory-address, implemented later on, right focused on getting work.)

to make iterator work, next() method be

public integer next(){     return tstarray[index++]; } 

this throws arrayindexoutofboundsexception if index large, whereas specification iterator says should throw nosuchelementexception. in order write

public integer next(){     if (index < tstarray.length)         return tstarray[index++];     throw new nosuchelementexception(); } 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -