1 22 23 package com.sosnoski.util.stack; 24 25 import java.util.Iterator ; 26 27 import com.sosnoski.util.ArrayRangeIterator; 28 29 40 41 public class ObjectStack extends StackBase 42 { 43 44 protected Object [] m_baseArray; 45 46 53 54 public ObjectStack(int size, int growth) { 55 super(size, growth, Object .class); 56 } 57 58 64 65 public ObjectStack(int size) { 66 super(size, Object .class); 67 } 68 69 72 73 public ObjectStack() { 74 this(DEFAULT_SIZE); 75 } 76 77 82 83 public ObjectStack(ObjectStack base) { 84 super(base); 85 } 86 87 93 94 protected Object getArray() { 95 return m_baseArray; 96 } 97 98 104 105 protected void setArray(Object array) { 106 m_baseArray = (Object []) array; 107 } 108 109 114 115 public void push(Object value) { 116 int index = getAddIndex(); 117 m_baseArray[index] = value; 118 } 119 120 126 127 public Object pop() { 128 if (m_countPresent > 0) { 129 Object value = m_baseArray[--m_countPresent]; 130 m_baseArray[m_countPresent] = null; 131 return value; 132 } else { 133 throw new ArrayIndexOutOfBoundsException 134 ("Attempt to pop empty stack"); 135 } 136 } 137 138 148 149 public Object pop(int count) { 150 if (count <= 0) { 151 throw new IllegalArgumentException ("Count must be greater than 0"); 152 } else if (m_countPresent >= count) { 153 m_countPresent -= count; 154 Object value = m_baseArray[m_countPresent]; 155 discardValues(m_countPresent, m_countPresent + count); 156 return value; 157 } else { 158 throw new ArrayIndexOutOfBoundsException 159 ("Attempt to pop past end of stack"); 160 } 161 } 162 163 172 173 public Object peek(int depth) { 174 if (m_countPresent > depth) { 175 return m_baseArray[m_countPresent - depth - 1]; 176 } else { 177 throw new ArrayIndexOutOfBoundsException 178 ("Attempt to peek past end of stack"); 179 } 180 } 181 182 189 190 public Object peek() { 191 return peek(0); 192 } 193 194 203 204 public final Iterator iterator() { 205 return ArrayRangeIterator.buildIterator(m_baseArray, 0, m_countPresent); 206 } 207 208 216 217 public Object [] toArray() { 218 return (Object []) buildArray(Object .class); 219 } 220 221 231 232 public Object [] toArray(Class type) { 233 return (Object []) buildArray(type); 234 } 235 236 241 242 public Object clone() { 243 return new ObjectStack(this); 244 } 245 } 246 | Popular Tags |