javaobjecthashmapiteratorinfinite-loop

Java Iterator.hasNext() always true


I've already checked other questions like this one but it doesn't seem that I always create a new iterator which checks always the same object.

This is the code

        Iterator<Map.Entry<Node, Float>> it = graph.nodeNeighboursIterator(e); 
        System.out.println("extracted node "+ e.getLabel() + " number of neighbours "+ e.sizeNeighbours());
        while(it.hasNext()) {
            System.out.print(i + " " + e.getLabel() + " " + it +"-");
            i++;
        }

the method graph.nodeNeighboursIterator does this

public Iterator<Map.Entry<Node, Float>> nodeNeighboursIterator(Node n) {
    return this.graph_weighted.get(n).entrySet().iterator();
}

the System.out.println("extracted node "+ e.getLabel() + " number of neighbours "+ e.sizeNeighbours()); prints the right number of neighbours but still the loop doesn't end his cycle, what do you think about it?


Solution

  • it.hasNext() checks if there is more data to be returned. This does not consume the data (in other words, does not iterate over the data). This operation is idempotent.

    This is the reason why your loop never ends.

    You need to actually consume the data by calling it.next(). it.hasNext() returns false if there are no more elements to return.