Stack
java.util.stack继承了Vector的子类,它提供了一系列的操作实现使用vector做栈的相关操作。
构造方法:
stack(): 无参构造,初始栈为空
主要方法:
boolean isEmpty(): 判空E peek(): 获取栈顶元素E pop(): 出栈E push(E item): 入栈int search(Object obj): 返回指定元素在栈中的位置,位置表示为到栈顶的距离
import java.util.Stack;public class StackMain {public static void main(String[] args) {Stack<Integer> stack = new Stack<>();stack.push(1);stack.push(2);stack.push(3);stack.push(4);stack.push(5);System.out.println(stack); // [1, 2, 3, 4, 5]System.out.println(stack.peek()); // 5System.out.println(stack.pop()); // 5System.out.println(stack); // [1, 2, 3, 4]System.out.println(stack.isEmpty()); // falseSystem.out.println(stack.search(2)); // 3}}
Queue
java.util.Queue是一个泛型接口,继承了Collection和Iterable两个接口。接口中的方法主要有:
boolean add(E e): 增加一个元索 ,如果队列已满,则抛出一个IIIegaISlabEepeplian异常E element(): 返回队列头部的元素,如果队列为空,则抛出一个NoSuchElementException异常boolean offer(E e): 将元素e插入到队列末尾,如果插入成功,则返回true;如果插入失败(即队列已满),则返回false;E peek(): 返回队列头部的元素,如果队列为空,则返回nullE poll():移除并返回队列头部的元素 如果队列为空,则返回nullE remove():移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
import java.util.LinkedList;import java.util.Queue;public class QueueMain {public static void main(String[] args) {Queue<Integer> queue = new LinkedList<Integer>();queue.add(1);queue.add(2);queue.add(3);queue.add(4);queue.add(5);System.out.println(queue); // [1, 2, 3, 4, 5]System.out.println(queue.peek()); // 1boolean flag = queue.offer(10);System.out.println(flag); // trueSystem.out.println(queue.peek()); // 1System.out.println(queue); // [1, 2, 3, 4, 5, 10]System.out.println(queue.poll()); // 1System.out.println(queue); //[2, 3, 4, 5, 10]System.out.println(queue.remove()); // 2System.out.println(queue); // [3, 4, 5, 10]}
