纸上得来终觉浅,绝知此事要躬行
--陆游 问渠那得清如许,为有源头活水来 --朱熹
Stack是栈,特性是先进后出(FILO,First In Last Out)。Stack是继承于Vector(矢量队列),由于Vector是同数组实现的,Stack也是通过数组而非链表。
Stack和Collection关系如下:
Stack示例代码:
Stack stack = new Stack();for(int i=1; i<6; i++){ stack.push(String.valueOf(i));//入栈}int pos = stack.search("2");//查找System.out.println("the postion of 2 is:"+pos);stack.pop();//出栈String val = (String)stack.peek();//栈顶数据System.out.println("peek:"+val);System.out.println(stack.pop());System.out.println("判断栈是否为空,出栈");while(!stack.isEmpty()){ System.out.println(stack.pop());}
结果:
the postion of 2 is:4
peek:4
4
判断栈是否为空,出栈
3
2
1
Java8中Stack源代码:
public class Stack<E> extends Vector<E> { public Stack() {//创建空栈} public E push(E item) {//入栈 addElement(item); return item;}//出栈public synchronized E pop() { E obj; int len = size(); obj = peek(); removeElementAt(len - 1); return obj;}//返回栈顶元素,但并不出栈public synchronized E peek() { int len = size(); if (len == 0) throw new EmptyStackException(); return elementAt(len - 1);}//判断栈是否为空public boolean empty() { return size() == 0;}//查找元素并返回栈深public synchronized int search(Object o) { int i = lastIndexOf(o); if (i >= 0) { return size() - i; }return -1;} //序列版本号private static final long serialVersionUID = 1224463164541339165L;}
版权声明:知识在于分享,技术在于交流,转载时请留一个博主的链接就好
时间: 2024-12-30 17:01:19