1.简介
栈是数据结构中一种很重要的数据结构类型,因为栈的后进先出功能是实际的开发中有很多的应用场景。Java API中提供了栈(Stacck)的实现,简单使用如下所示
package com.test.collections; import java.util.Stack; public class StackTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Stack<String> stack = new Stack<String>(); stack.add("China"); stack.add("Japan"); stack.add("Russia"); stack.add("England"); System.out.println(stack.size()+"<="+stack.capacity()); System.out.println(stack.elementAt(0)); System.out.println(stack.get(0)); System.out.println(stack.peek()); System.out.println(stack.push("France")); System.out.println(stack.pop()); System.out.println(stack.iterator()); System.out.println(stack.empty()); System.out.println(stack.isEmpty());<br> System.out.println(stack.search("Russia")); } } |
2.继承结构
Stack类继承了Vector类,而Vector类继承了AbstractList抽象类,实现了List接口,Cloneable接口,RandomAcces接口以及Serializable接口,需要指出的Vector内部还有两个内部类ListItr和Itr,Itr在继承Vector的同时实现了Iterator接口,而ListItr在继承了Itr类的同时实现了ListIterator接口。
3.源码解读
通过Stack类发现含有的方法有pop(),peek(),push(Object),search(Object),empty()方法,其他值的方法是从Vector类继承而来,通过源码可以发现Vector有几个属性值:protected Object[] elementData,protected int elementCount;protected int capacityIncrement;private static final int MAX_ARRAY_SIZE = 2147483639;通过这几属性我们可以发现,Stack底层是采用数组来实现的,elementData用于保存Stack中的每个元素;elementCount用于动态的保存元素的个数,capacityIncrement用来保存Stack的容量(一般情况下应该是大于elementCount);MAX_ARRAY_SIZE 用于限制Stack能够保存的最大值数量。
a.removeElementAt() public synchronized void removeElementAt(int paramInt) { this.modCount += 1; if (paramInt >= this.elementCount) throw new ArrayIndexOutOfBoundsException(paramInt + " >= " + this.elementCount); if (paramInt < 0) throw new ArrayIndexOutOfBoundsException(paramInt); int i = this.elementCount - paramInt - 1; if (i > 0) System.arraycopy(this.elementData, paramInt + 1, this.elementData, paramInt, i); this.elementCount -= 1; this.elementData[this.elementCount] = null; } |