栈是Vector的一个子类,它实现了一个标准的后进先出的栈
堆栈只定义了默认构造函数,用来创建一个空栈。 堆栈除了包括由Vector定义的所有方法,也定义了自己的一些方法——Stack()
除了由Vector定义的所有方法,自己也定义了一些方法:

序号 方法描述
1 boolean empty()
测试堆栈是否为空。
2 Object peek( )
查看堆栈顶部的对象,但不从堆栈中移除它。
3 Object pop( )
移除堆栈顶部的对象,并作为此函数的值返回该对象。
4 Object push(Object element)
把项压入堆栈顶部。
5 int search(Object element)
返回对象在堆栈中的位置,以 1 为基数。
  1. import java.util.*;
  2. public class StackDemo {
  3. static void showpush(Stack<Integer> st, int a) {
  4. st.push(new Integer(a));
  5. System.out.println("push(" + a + ")");
  6. System.out.println("stack: " + st);
  7. }
  8. static void showpop(Stack<Integer> st) {
  9. System.out.print("pop -> ");
  10. Integer a = (Integer) st.pop();
  11. System.out.println(a);
  12. System.out.println("stack: " + st);
  13. }
  14. public static void main(String args[]) {
  15. Stack<Integer> st = new Stack<Integer>();
  16. System.out.println("stack: " + st);
  17. showpush(st, 42);
  18. showpush(st, 66);
  19. showpush(st, 99);
  20. showpop(st);
  21. showpop(st);
  22. showpop(st);
  23. try {
  24. showpop(st);
  25. } catch (EmptyStackException e) {
  26. System.out.println("empty stack");
  27. }
  28. }
  29. }
  30. stack: [ ]
  31. push(42)
  32. stack: [42]
  33. push(66)
  34. stack: [42, 66]
  35. push(99)
  36. stack: [42, 66, 99]
  37. pop -> 99
  38. stack: [42, 66]
  39. pop -> 66
  40. stack: [42]
  41. pop -> 42
  42. stack: [ ]
  43. pop -> empty stack

队列

队列是一种特殊的线性表,它只允许在表的前端进行删除操作,而在表的后端进行插入操作
LinkedList类实现了Queue接口,因此我们可以把LinkedList当成Queue来用

import java.util.LinkedList;
import java.util.Queue;

/**
poll,remove区别:
remove() 和 poll() 方法都是从队列中删除第一个元素。remove() 的行为与 Collection 接口的版本相似, 但是新的 poll() 方法在用空集合调用时不是抛出异常,只是返回 null。因此新的方法更适合容易出现异常条件的情况。

peek,element区别:
element() 和 peek() 用于在队列的头部查询元素。与 remove() 方法类似,在队列为空时, element() 抛出一个异常,而 peek() 返回 null。
*/

public class Main {
    public static void main(String[] args) {
        //add()和remove()方法在失败的时候会抛出异常(不推荐)
        Queue<String> queue = new LinkedList<String>();
        //添加元素
        queue.offer("a");
        queue.offer("b");
        queue.offer("c");
        queue.offer("d");
        queue.offer("e");
        for(String q : queue){
            System.out.println(q);
        }
        System.out.println("===");
        System.out.println("poll="+queue.poll()); //返回第一个元素,并在队列中删除
        for(String q : queue){
            System.out.println(q);
        }
        System.out.println("===");
        System.out.println("element="+queue.element()); //返回第一个元素 
        for(String q : queue){
            System.out.println(q);
        }
        System.out.println("===");
        System.out.println("peek="+queue.peek()); //返回第一个元素 
        for(String q : queue){
            System.out.println(q);
        }
    }
}

a
b
c
d
e
===
poll=a
b
c
d
e
===
element=b
b
c
d
e
===
peek=b
b
c
d
e