【发布时间】: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