Stack源码探讨(基于JDK1.8)

来源:互联网 发布:怎么登录我的淘宝账号 编辑:程序博客网 时间:2024/06/03 11:16
Stack简介

Stack是栈。它的特性是:先进后出(FILO, First In Last Out)。
java工具包中的Stack是继承于Vector(矢量队列)的,由于Vector是通过数组实现的,这就意味着,Stack也是通过数组实现的,而非链表。当然,我们也可以将LinkedList当作栈来使用。
Stack是线程安全的。建议在学习Stack之前先学习Vector类。

Stack结构
  1. public class Stack<E> extends Vector<E>

Vector结构
  1. public class Vector<E>
  2. extends AbstractList<E>
  3. implements List<E>, RandomAccess, Cloneable, java.io.Serializable


Stack的
  1. package java.util;
  2. public
  3. class Stack<E> extends Vector<E> {
  4. // 版本ID。这个用于版本升级控制,这里不须理会!
  5. private static final long serialVersionUID = 1224463164541339165L;
  6. // 构造函数
  7. public Stack() {
  8. }
  9. // push函数:将元素存入栈顶
  10. public E push(E item) {
  11. // 将元素存入栈顶。
  12. // addElement()的实现在Vector.java中
  13. addElement(item);
  14. return item;
  15. }
  16. // pop函数:返回栈顶元素,并将其从栈中删除
  17. public synchronized E pop() {
  18. E obj;
  19. int len = size();
  20. obj = peek();
  21. // 删除栈顶元素,removeElementAt()的实现在Vector.java中
  22. removeElementAt(len - 1);
  23. return obj;
  24. }
  25. // peek函数:返回栈顶元素,不执行删除操作
  26. public synchronized E peek() {
  27. int len = size();
  28. if (len == 0)
  29. throw new EmptyStackException();
  30. // 返回栈顶元素,elementAt()具体实现在Vector.java中
  31. return elementAt(len - 1);
  32. }
  33. // 栈是否为空
  34. public boolean empty() {
  35. return size() == 0;
  36. }
  37. // 查找“元素o”在栈中的位置:由栈顶向下数
  38. public synchronized int search(Object o) {
  39. // 获取元素索引,elementAt()具体实现在Vector.java中
  40. int i = lastIndexOf(o);
  41. if (i >= 0) {
  42. return size() - i;
  43. }
  44. return -1;
  45. }
  46. }

关于方法public synchronized int search(Object o)有必要深入的跟进源码。
  1. public synchronized int search(Object o) {
  2. int i = lastIndexOf(o);
  3. if (i >= 0) {
  4. return size() - i;
  5. }
  6. return -1;
  7. }

跟进lastIndexOf(o);
  1. public synchronized int lastIndexOf(Object o) {
  2. return lastIndexOf(o, elementCount-1);
  3. }
  1. public synchronized int lastIndexOf(Object o, int index) {
  2. if (index >= elementCount)
  3. throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
  4. if (o == null) {
  5. for (int i = index; i >= 0; i--)
  6. if (elementData[i]==null)
  7. return i;
  8. } else {
  9. for (int i = index; i >= 0; i--)
  10. if (o.equals(elementData[i]))
  11. return i;
  12. }
  13. return -1;
  14. }
可以看到,查找元素时,是从数组的尾部开始遍历的。


测试demo
  1. public class TestStack {
  2. public static void main(String[] args) {
  3. Stack s = new Stack();
  4. s.push("a");
  5. s.push("b");
  6. s.push("c");
  7. s.push("d");
  8. System.out.println(s.search("a"));
  9. }
  10. }
控制台输出:4