KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tonbeller > wcf > tree > NodeIterator


1 /*
2  * ====================================================================
3  * This software is subject to the terms of the Common Public License
4  * Agreement, available at the following URL:
5  * http://www.opensource.org/licenses/cpl.html .
6  * Copyright (C) 2003-2004 TONBELLER AG.
7  * All Rights Reserved.
8  * You must accept the terms of that agreement to use this software.
9  * ====================================================================
10  *
11  *
12  */

13 package com.tonbeller.wcf.tree;
14
15 import java.util.ArrayList JavaDoc;
16 import java.util.Iterator JavaDoc;
17 import java.util.List JavaDoc;
18
19 /**
20  * flat view of a tree model in pre- or postorder
21  *
22  * @author av
23  */

24 public class NodeIterator implements Iterator JavaDoc {
25
26   private boolean preorder;
27
28   private TreeModel tm;
29   private List JavaDoc list = new ArrayList JavaDoc();
30   private Iterator JavaDoc iter;
31
32   /**
33    * traverses the whole tree
34    * @param tm
35    * @param preorder
36    */

37   public NodeIterator(TreeModel tm, boolean preorder) {
38     this.tm = tm;
39     this.preorder = preorder;
40     recurse(tm.getRoots());
41     iter = list.iterator();
42   }
43
44   /**
45    * traverses the subtree containing node and all children of node
46    * @param tm
47    * @param preorder
48    * @param root
49    */

50   public NodeIterator(TreeModel tm, Object JavaDoc root, boolean preorder) {
51     this.tm = tm;
52     this.preorder = preorder;
53     recurse(new Object JavaDoc[]{root});
54     iter = list.iterator();
55   }
56
57   private void recurse(Object JavaDoc[] nodes) {
58     for (int i = 0; i < nodes.length; i++) {
59       Object JavaDoc node = nodes[i];
60       if (preorder)
61         list.add(node);
62       if (tm.hasChildren(node))
63         recurse(tm.getChildren(node));
64       if (!preorder)
65         list.add(node);
66     }
67   }
68
69   public boolean hasNext() {
70     return iter.hasNext();
71   }
72
73   public Object JavaDoc next() {
74     return iter.next();
75   }
76
77   public void remove() {
78     iter.remove();
79   }
80
81   public void rewind() {
82     iter = list.iterator();
83   }
84
85 }
86
Popular Tags