android和java不提供堆栈的实现,只提供了list,vector,deque得存储结构,对于以前做面向过程语言的员来说,总觉得缺少了些什么;
Stack.java文件:
public class Stack{ Vector vector = new Vector(); public T pop() { T t = null; if (!isBottom()) { t = vector.lastElement(); int pos = vector.lastIndexOf(t);// vector.remove(t); vector.removeElementAt(pos); } return t; } public void push(T t) { vector.addElement(t); } public boolean isBottom() { if (vector.isEmpty()) { return true; } return false; } public int size() { return vector.size(); }}
main.java文件:
public class main { public static void main(String[] args) { // TODO Auto-generated method stub Stackstack = new Stack (); stack.push("test1"); stack.push("test2"); stack.push("test3"); System.out.println("size=" + stack.size()); for (int iLoop = 0; iLoop < 4; iLoop++) { if (!stack.isBottom()) { System.out.println(stack.pop()); } else { System.out.println("isbottom"); } } System.out.println("size=" + stack.size()); }}
打印结果:
size=3test3test2test1isbottomsize=0
以上结果实现了栈式管理的先入后出,由于其内部实现是vector方式所以其长度是动态增加的!