简体   繁体   中英

Self-made Iterator bug

I have to make myself a custom linked list, and I have problems with the Iterator. The next() method is working correctly, but strangely, the hasNext() method does not.
Here is the code:

public Iterator<T> iterator() {
    final Node<T> currentNode = this.iteratorNode;
    final MyLinkedList<T> list = this;
    final Node<T> firstNode = this.firstNode;

    return new Iterator<T>() {
        @Override
        public boolean hasNext() {
            if (list.isEmpty()) {
                return false;
            } else if (currentNode == null){
                list.setIteratorNode(firstNode);
                return true;
            } else if (currentNode.nextNode == null){
                return false;
            }
            list.setIteratorNode(currentNode.nextNode);
            return true;
        }

        @Override
        public T next() {
            if (list.isEmpty()){
                return null;
            } else if (currentNode == null){
                list.setIteratorNode(firstNode);
                return firstNode.data;
            } else if (currentNode.nextNode == null) {
                return null;
            }
            list.setIteratorNode(currentNode.nextNode);
            return currentNode.nextNode.data;
        }
    };
}

The components of the code (like the isEmpty() and setIteratorNode() methods are working correctly. What really makes this weird (in my opinion), is that I basically do the same thing in next() as in hasNext() .

Any help would be greatly appreciated.

Your flaw is that hasNext should be idempotent. It should not update the location of the current position. Hence the code list.setIteratorNode(currentNode.nextNode); should not exist in hasNext

Addition:

Move the variables: currentNode and firstNode into your Iterator class. Make currentNode non-final. currentNode should be initialized to null . The only thing the Iterator should modify is its own currentNode .

You should remove the line

list.setIteratorNode(currentNode.nextNode);

from your hasNext() method. You only want to update the position of the iterator in the next() method.

Incidentally, I don't like the fact that you seem to store the position of the iterator in the list. This makes it impossible to have two iterators on the same list which have different positions. You should store the position in the iterator itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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