我想使用訪問者模式來實現樹。所以我做了一個主類Node
和擴展該類的其他類(例如Node1
,Node2
,Node3
)。在Node
我有一個字符串和ArrayList
的Nodes
這是該節點的子項列表。所以,我實現了一個訪客有3個功能visit(Node1 x)
,...在main
我想打電話給接受每節點:訪問者模式接受不識別對象的類
SomeVisitor v = new SomeVisitor();
Node n = makeTree();
Iterator<? extends Node> it = n.children.iterator();
while(it.hasNext()) {
System.out.println(it.next().getClass());
it.next.accept(v);
}
這不起作用,因爲即使.getClass
返回特定類 我的意思是,節點1 ,2或3,我得到的錯誤是it.next
是 型節點,但我沒有在我的樹的任何節點對象,我並沒有實現 visit(Node)
只是visit(Node 1,2,3)
你必須在你的發佈代碼位的錯誤:你調用'it.next ()'在同一次迭代中兩次。 – toto2 2011-12-27 16:02:12