1 9 10 18 19 package org.jboss.portal.format.util; 20 21 import java.util.Collections ; 22 import java.util.Iterator ; 23 24 36 public abstract class Stack 37 { 38 39 40 protected int ptr = 0; 41 42 43 protected Key[] stack; 44 45 46 private KeyIterator iterator = new KeyIterator(); 47 48 51 public Stack(int initalCapacity) 52 { 53 this.stack = new Key[initalCapacity]; 54 for (int i = 0; i < stack.length; i++) 55 { 56 this.stack[i] = createKey(); 57 } 58 } 59 60 63 public final void reset() 64 { 65 ptr = 0; 66 } 67 68 71 public final Key push() 72 { 73 if (ptr == stack.length) 74 { 75 enlarge(); 76 } 77 return stack[ptr++]; 78 } 79 80 83 public Key peek(int level) 84 { 85 level = ptr - level; 86 return level >= 0 ? stack[level] : null; 87 } 88 89 92 public final Iterator pop(Key candidate) 93 { 94 if (ptr > 0) 95 { 96 iterator.from = ptr - 1; 97 for (Key key = stack[--ptr];!equals(candidate, key) && ptr >= 1;key = stack[--ptr]) 98 { 99 ; 100 } 101 iterator.to = ptr - 1; 102 return iterator; 103 } 104 else 105 { 106 return Collections.EMPTY_LIST.iterator(); 108 } 109 } 110 111 114 protected abstract Key createKey(); 115 116 119 protected abstract boolean equals(Key key1, Key key2); 120 121 124 protected void enlarge() 125 { 126 Key[] tmp = new Key[stack.length + 3]; 127 System.arraycopy(stack, 0, tmp, 0, stack.length); 128 for (int i = stack.length;i < tmp.length;i++) 129 { 130 tmp[i] = createKey(); 131 } 132 stack = tmp; 133 } 134 135 138 public class KeyIterator implements Iterator 139 { 140 private int from; 141 private int to; 142 public boolean hasNext() 143 { 144 return from > to; 145 } 146 public Object next() 147 { 148 return stack[from--]; 149 } 150 public void remove() 151 { 152 throw new UnsupportedOperationException (); 153 } 154 } 155 156 159 public interface Key 160 { 161 } 162 } 163 | Popular Tags |