[英]Java List Iterator does not seem to be iterating properly
我正在編寫一個程序,該程序采用二叉樹並按順序遍歷它。 為此,我的迭代器類遍歷了樹並將元素添加到列表中,然后遍歷列表。 在調試我的代碼時,我發現該列表包含應有的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());
}
}
}
讓我知道是否也應該添加二叉樹實現。
public Object next() {
// vvvvvvvvvvv
return decorationList.iterator().next();
}
每次調用這些方法時,您都在創建一個新的Iterator。 這就是為什么您看到自己的行為。 每次hasNext
或next
,您都將創建一個從0開始的新Iterator。
相反,如果要編寫一個僅委托給另一個迭代器的迭代器,則應在構造函數中一次創建它:
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();
}
...
}
另外:通常,我們不使用原始類型 。 如果BinaryTree
是非泛型的,則應實現Iterator<Object>
而不是原始類型。 由於decorationList
是List<String>
因此您似乎應該實現Iterator<String>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.