【问题标题】:Java List Iterator does not seem to be iterating properlyJava List Iterator 似乎没有正确迭代
【发布时间】:2014-11-20 02:52:06
【问题描述】:

我正在编写一个程序,它采用二叉树并按顺序遍历它。为此,我的迭代器类遍历树并将元素添加到列表中,然后迭代列表。在调试我的代码时,我发现列表应该包含 4 个不同的元素,但是在打印列表时在main 中,我一遍又一遍地得到tinsel(列表的第一个元素)无限循环。因此,迭代器根本没有迭代;它卡在第一个元素上。

迭代器类:

import java.util.*;

@SuppressWarnings("rawtypes")
public class TreeIterator implements Iterator{

    BinaryTree BT;

    TreeIterator(BinaryTree BT){
        this.BT=BT;
        inOrder(BT.root);
    }

    private List<String> decorationList = new ArrayList<String>();

    private void inOrder(Node root){
        if(root==null) return;
        inOrder(root.left);
        String temp = root.decoration;
        decorationList.add(temp);
        inOrder(root.right);
    }

    public boolean hasNext() {
        return decorationList.iterator().hasNext();
    }

    public Object next() {
        return decorationList.iterator().next();
    }

    public void remove() {
        // this method is not implemented           
    }

}

主要功能:

public class Main {
    public static void main(String[] args) {

        // build a test tree
        //
        //       star
        //      /    \
        // tinsel    red balls
        //      \
        //       lights
        BinaryTree BT = new BinaryTree();
        BT.root = new Node();
        BT.root.decoration = "star";
        BT.root.left = new Node();
        BT.root.left.decoration = "tinsel";
        BT.root.left.right = new Node();
        BT.root.left.right.decoration = "lights";
        BT.root.right = new Node();
        BT.root.right.decoration = "red balls";


        TreeIterator TI = BT.createIterator();
        while(TI.hasNext()){
            System.out.println(TI.next());
        }
    }
}

如果我也应该添加二叉树实现,请告诉我。

【问题讨论】:

  • 这个@SuppressWarnings("rawtypes") 是邪恶的。另外,为什么每次通话都再次收到iterator

标签: java list iterator listiterator


【解决方案1】:
public Object next() {
    //                   vvvvvvvvvvv
    return decorationList.iterator().next();
}

每次调用这些方法时,您都会创建一个新的迭代器。这就是为什么你看到你的行为。每次调用 hasNextnext,都会创建一个从 0 开始的新迭代器。

相反,如果您正在编写一个简单地委托给另一个迭代器的迭代器,您应该在构造函数中创建一次:

class IteratorDelegator<T> implements Iterator<T> {
    private final Iterator<? extends T> delegate;

    IteratorDelegator(Iterable<? extends T> iterable) {
        this.delegate = iterable.iterator();
    }

    @Override
    public T next() {
        return delegate.next();
    }

    ...
}

另外:一般我们不使用raw types。如果您的 BinaryTree 是非泛型的,您应该实现 Iterator&lt;Object&gt; 而不是原始类型。由于decorationListList&lt;String&gt;,看来您应该实现Iterator&lt;String&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 2013-03-17
    • 2010-09-08
    • 2016-12-26
    相关资源
    最近更新 更多