简体   繁体   English

Java Iterator.hasNext() 始终为真

[英]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方法graph.nodeNeighboursIterator执行此操作

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()); 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?打印了正确数量的邻居,但循环仍然没有结束他的循环,你怎么看?

it.hasNext() checks if there is more data to be returned. it.hasNext()检查是否有更多数据要返回。 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.next()来实际使用数据。 it.hasNext() returns false if there are no more elements to return.如果没有更多元素要返回,则it.hasNext()返回 false。

You need revise your code to like below您需要修改您的代码以如下所示

while(it.hasNext()) {
    it.next();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM