| 1 |
|
package net.sf.tacos.components.tree; |
| 2 |
|
|
| 3 |
|
import java.util.ArrayList; |
| 4 |
|
import java.util.Collection; |
| 5 |
|
import java.util.Collections; |
| 6 |
|
import java.util.Iterator; |
| 7 |
|
import java.util.List; |
| 8 |
|
import java.util.Stack; |
| 9 |
|
|
| 10 |
|
|
| 11 |
|
|
| 12 |
|
|
| 13 |
|
public abstract class TreeIterator implements Iterator { |
| 14 |
|
|
| 15 |
0 |
private final Stack todo = new Stack(); |
| 16 |
0 |
private int depth = 0; |
| 17 |
0 |
private int previousDepth = 0; |
| 18 |
0 |
private int markers = 0; |
| 19 |
|
|
| 20 |
|
|
| 21 |
|
|
| 22 |
|
|
| 23 |
|
|
| 24 |
|
public TreeIterator(Object rootElement) |
| 25 |
0 |
{ |
| 26 |
0 |
todo.push(rootElement); |
| 27 |
0 |
} |
| 28 |
|
|
| 29 |
|
|
| 30 |
|
|
| 31 |
|
|
| 32 |
|
|
| 33 |
|
public TreeIterator(Collection rootElements) |
| 34 |
0 |
{ |
| 35 |
0 |
push(rootElements); |
| 36 |
0 |
} |
| 37 |
|
|
| 38 |
|
|
| 39 |
|
|
| 40 |
|
|
| 41 |
|
|
| 42 |
|
public int getDepth() |
| 43 |
|
{ |
| 44 |
0 |
return depth; |
| 45 |
|
} |
| 46 |
|
|
| 47 |
|
|
| 48 |
|
|
| 49 |
|
|
| 50 |
|
|
| 51 |
|
public int getPreviousDepth() |
| 52 |
|
{ |
| 53 |
0 |
return previousDepth; |
| 54 |
|
} |
| 55 |
|
|
| 56 |
|
|
| 57 |
|
|
| 58 |
|
|
| 59 |
|
|
| 60 |
|
public boolean hasNext() |
| 61 |
|
{ |
| 62 |
0 |
return !todo.isEmpty() && todo.size() != markers; |
| 63 |
|
} |
| 64 |
|
|
| 65 |
|
|
| 66 |
|
|
| 67 |
|
|
| 68 |
|
|
| 69 |
|
public Object next() |
| 70 |
|
{ |
| 71 |
|
Object node; |
| 72 |
|
do { |
| 73 |
0 |
node = todo.pop(); |
| 74 |
0 |
if (node == MARKER) { |
| 75 |
0 |
markers--; |
| 76 |
|
} |
| 77 |
0 |
} while(node == MARKER); |
| 78 |
0 |
previousDepth = depth; |
| 79 |
0 |
depth = markers; |
| 80 |
0 |
Collection children = getChildren(node); |
| 81 |
0 |
if (!children.isEmpty()) { |
| 82 |
0 |
todo.push(MARKER); |
| 83 |
0 |
markers++; |
| 84 |
0 |
push(children); |
| 85 |
|
} |
| 86 |
0 |
return node; |
| 87 |
|
} |
| 88 |
|
|
| 89 |
|
|
| 90 |
|
|
| 91 |
|
|
| 92 |
|
|
| 93 |
|
private void push(Collection elements) |
| 94 |
|
{ |
| 95 |
0 |
List rev = new ArrayList(elements); |
| 96 |
0 |
Collections.reverse(rev); |
| 97 |
0 |
todo.addAll(rev); |
| 98 |
0 |
} |
| 99 |
|
|
| 100 |
|
|
| 101 |
|
|
| 102 |
|
|
| 103 |
|
|
| 104 |
|
|
| 105 |
|
protected abstract Collection getChildren(Object node); |
| 106 |
|
|
| 107 |
|
|
| 108 |
|
|
| 109 |
|
|
| 110 |
|
|
| 111 |
|
public void remove() |
| 112 |
|
{ |
| 113 |
0 |
throw new UnsupportedOperationException(); |
| 114 |
|
} |
| 115 |
|
|
| 116 |
0 |
private final static Object MARKER = new Object(); |
| 117 |
|
|
| 118 |
|
} |