01: /*
02: * Copyright (C) 2004, 2005 Joe Walnes.
03: * Copyright (C) 2006, 2007 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 02. September 2004 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.core.util;
13:
14: /**
15: * An array-based stack implementation.
16: *
17: * @author Joe Walnes
18: * @author Jörg Schaible
19: */
20: public final class FastStack {
21:
22: private Object[] stack;
23: private int pointer;
24:
25: public FastStack(int initialCapacity) {
26: stack = new Object[initialCapacity];
27: }
28:
29: public Object push(Object value) {
30: if (pointer + 1 >= stack.length) {
31: resizeStack(stack.length * 2);
32: }
33: stack[pointer++] = value;
34: return value;
35: }
36:
37: public void popSilently() {
38: stack[--pointer] = null;
39: }
40:
41: public Object pop() {
42: final Object result = stack[--pointer];
43: stack[pointer] = null;
44: return result;
45: }
46:
47: public Object peek() {
48: return pointer == 0 ? null : stack[pointer - 1];
49: }
50:
51: public int size() {
52: return pointer;
53: }
54:
55: public boolean hasStuff() {
56: return pointer > 0;
57: }
58:
59: public Object get(int i) {
60: return stack[i];
61: }
62:
63: private void resizeStack(int newCapacity) {
64: Object[] newStack = new Object[newCapacity];
65: System.arraycopy(stack, 0, newStack, 0, Math.min(pointer,
66: newCapacity));
67: stack = newStack;
68: }
69:
70: public String toString() {
71: StringBuffer result = new StringBuffer("[");
72: for (int i = 0; i < pointer; i++) {
73: if (i > 0) {
74: result.append(", ");
75: }
76: result.append(stack[i]);
77: }
78: result.append(']');
79: return result.toString();
80: }
81: }
|