R4LPH R4LPH - 1 month ago 6
Java Question

For each loop of Iterator skips first element

For school I had to made a kind of linked list like queue.
My nodes have 3 attributes:


  • Node left (Node left of the node)

  • Node right (Node right of the node)

  • Object item (The object that is stored in the list)



I also have to make the list iterable so implemented that interface.

The problem I have now is that if there are for example 4 items in the list, it only shows 3 of them.

So if for example the list has 4 strings in it, 'a', 'b', 'c' and 'd' the output is:

b
c
d


My hasNext method looks like:

@Override
public boolean hasNext() {
return node.getRight() != null;
}


and my next method looks like:

@Override
public T next() {
node = node.getRight();
Object item = node.getItem();
return (T)item;
}


If I return the item of the node instead of the node on the right I get

a
b
c


as return but that is also not good because it skips the last one. And when you read the API next should return the next value so I guess my next method has to be as it is.

Answer Source

The iterator's methods should be implemented as this:

@Override
public T next() {
    Object item = node.getItem();
    node = node.getRight();
    return (T)item;
}

@Override
public boolean hasNext() {
    return node != null;
}

Just think about other iterators. At the first call of next() they return the first element and THEN they move forward to the second. When you are pointing to the last element, next() should return it and move forward (i.e. point to null). To be able to do this, the test inside of hasNext should be on the current item, not on the next, otherwise you could not get the last element.