Stack

java.util.stack继承了Vector的子类,它提供了一系列的操作实现使用vector做栈的相关操作。

  • 构造方法:

    • stack(): 无参构造,初始栈为空
  • 主要方法:

    • boolean isEmpty(): 判空
    • E peek(): 获取栈顶元素
    • E pop(): 出栈
    • E push(E item): 入栈
    • int search(Object obj): 返回指定元素在栈中的位置,位置表示为到栈顶的距离
  1. import java.util.Stack;
  2. public class StackMain {
  3. public static void main(String[] args) {
  4. Stack<Integer> stack = new Stack<>();
  5. stack.push(1);
  6. stack.push(2);
  7. stack.push(3);
  8. stack.push(4);
  9. stack.push(5);
  10. System.out.println(stack); // [1, 2, 3, 4, 5]
  11. System.out.println(stack.peek()); // 5
  12. System.out.println(stack.pop()); // 5
  13. System.out.println(stack); // [1, 2, 3, 4]
  14. System.out.println(stack.isEmpty()); // false
  15. System.out.println(stack.search(2)); // 3
  16. }
  17. }

Queue

java.util.Queue是一个泛型接口,继承了Collection和Iterable两个接口。接口中的方法主要有:

  • boolean add(E e): 增加一个元索 ,如果队列已满,则抛出一个IIIegaISlabEepeplian异常
  • E element(): 返回队列头部的元素,如果队列为空,则抛出一个NoSuchElementException异常
  • boolean offer(E e): 将元素e插入到队列末尾,如果插入成功,则返回true;如果插入失败(即队列已满),则返回false;
  • E peek(): 返回队列头部的元素,如果队列为空,则返回null
  • E poll():移除并返回队列头部的元素 如果队列为空,则返回null
  • E remove():移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
  1. import java.util.LinkedList;
  2. import java.util.Queue;
  3. public class QueueMain {
  4. public static void main(String[] args) {
  5. Queue<Integer> queue = new LinkedList<Integer>();
  6. queue.add(1);
  7. queue.add(2);
  8. queue.add(3);
  9. queue.add(4);
  10. queue.add(5);
  11. System.out.println(queue); // [1, 2, 3, 4, 5]
  12. System.out.println(queue.peek()); // 1
  13. boolean flag = queue.offer(10);
  14. System.out.println(flag); // true
  15. System.out.println(queue.peek()); // 1
  16. System.out.println(queue); // [1, 2, 3, 4, 5, 10]
  17. System.out.println(queue.poll()); // 1
  18. System.out.println(queue); //[2, 3, 4, 5, 10]
  19. System.out.println(queue.remove()); // 2
  20. System.out.println(queue); // [3, 4, 5, 10]
  21. }