一、前言
关于jsr源码包中com.bea.xml.stream.util.Stack堆栈类,基于java.util.AbstractCollection抽象类和对象数组实现自定义堆栈类,详情见源码说明。
二、源码说明
package com.bea.xml.stream.util;@b@@b@import java.util.AbstractCollection;@b@import java.util.EmptyStackException;@b@import java.util.Iterator;@b@@b@public final class Stack extends AbstractCollection@b@{@b@ private Object[] values;@b@ private int pointer;@b@@b@ public Stack()@b@ {@b@ this(15);@b@ }@b@@b@ public Stack(int size) {@b@ if (size < 0) throw new IllegalArgumentException();@b@ this.values = new Object[size];@b@ this.pointer = 0;@b@ }@b@@b@ private Stack(Object[] values, int pointer) {@b@ this.values = values;@b@ this.pointer = pointer;@b@ }@b@@b@ private void resize() {@b@ if (this.pointer == 0) {@b@ this.values = new Object[1];@b@ return;@b@ }@b@ Object[] o = new Object[this.pointer * 2];@b@ System.arraycopy(this.values, 0, o, 0, this.pointer);@b@ this.values = o;@b@ }@b@@b@ public boolean add(Object o) {@b@ push(o);@b@ return true;@b@ }@b@@b@ public void clear() {@b@ Object[] v = this.values;@b@ while (this.pointer > 0)@b@ v[(--this.pointer)] = null;@b@ }@b@@b@ public boolean isEmpty() {@b@ return (this.pointer == 0); }@b@@b@ public Iterator iterator() {@b@ Object[] o = new Object[this.pointer];@b@ System.arraycopy(this.values, 0, o, 0, this.pointer);@b@ return new ArrayIterator(o);@b@ }@b@@b@ public Object clone() {@b@ Object[] newValues = new Object[this.pointer];@b@ System.arraycopy(this.values, 0, newValues, 0, this.pointer);@b@ return new Stack(newValues, this.pointer); }@b@@b@ public int size() {@b@ return this.pointer; }@b@@b@ public void push(Object o) {@b@ if (this.pointer == this.values.length) resize();@b@ this.values[(this.pointer++)] = o;@b@ }@b@@b@ public Object pop() {@b@ try {@b@ Object o = this.values[(--this.pointer)];@b@ this.values[this.pointer] = null;@b@ return o;@b@ }@b@ catch (ArrayIndexOutOfBoundsException aioobe)@b@ {@b@ if (this.pointer < 0) this.pointer = 0;@b@ throw new EmptyStackException();@b@ }@b@ }@b@@b@ public Object peek() {@b@ try {@b@ return this.values[(this.pointer - 1)];@b@ } catch (ArrayIndexOutOfBoundsException aioobe) {@b@ throw new EmptyStackException();@b@ }@b@ }@b@}