迭代器 hasNext() 方法

问题描述

为什么我们将 hasNext 方法实现为

public boolean hasNext() {
            if(current != null) 
                return true;
            return false;
}

代替

public boolean hasNext() {
            if(current.getNext() != null) 
                return true;
            return false;
}

解决方法

我不知道我们是谁,但请考虑以下内容。

public boolean hasNext() {
            if(current != null) 
                return true;
            return false;
}

在前一种情况下,next() 将返回值并更新当前值。

public boolean hasNext() {
            if(current.getNext() != null) 
                return true;
            return false;
}

在这种情况下,如果 getNext() 为空,您仍然需要返回当前值(例如 current.getValue()),因此您会错过最后一个。

但请记住,hasNext()next() 不能相互隔离地工作。因此,这取决于两者的实现方式,以判断其中一种方法是否有意义。