0

I am new to the whole "iterator" concept in Java and need help with implementing it in my code. Here is the code:

class IteratorExample {

int tstArray [];

IteratorExample(){

}

public void addNum(int num){

   tstArray[0] = num; //And yes, I can only add one number at the moment, but it
                      is not what I want to 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 is the code written so far. I want to make it so I can add a number to an array using the addNum() method and then display it from main using system.print (and yes, I am aware that I need a toString method in order for the numbers to come up instead of the memory-address, that will be implemented later on, right now I am only focused on getting this to work.)

6
  • 2
    What is your actual question here? Commented Oct 2, 2015 at 23:24
  • "And yes, I can only add one number at the moment, but it is not what I want to focus on right now." - Actually, it is what you should be focusing on. 'Cos it includes infrastructure that the iterator needs. Commented Oct 2, 2015 at 23:27
  • 1
    Why are you trying to add an iterator to a non-collection type? Commented Oct 2, 2015 at 23:27
  • I am trying to compare the run speed between an array and and arraylist with iterators. It is unconventional(and may I add not practical?) but that is the real reason. Commented Oct 2, 2015 at 23:29
  • you can't print the memory address btw Commented Oct 2, 2015 at 23:30

1 Answer 1

2

To make the Iterator work, the next() method could be

public Integer next(){
    return tstArray[index++];
}

This throws an ArrayIndexOutOfBoundsException if the index is too large, whereas the specification for Iterator says it should throw a NoSuchElementException. In order to do it properly you could write

public Integer next(){
    if (index < tstArray.length)
        return tstArray[index++];
    throw new NoSuchElementException();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.