【Java队列】Queue,Deque及其子类使用方法解析

Queue介绍

队列,先进先出。

Queue接口与List、Set同一级别,都是继承了Collection接口。
在这里插入图片描述

Queue使用

常用方法解释
offer(e)添加元素,成功为true,失败为false
poll ()返回队列头,出队列,队列空为null
peek()返回队列头,不出队列,队列空为null

Deque介绍

双端队列,可在两头入队和出队
在这里插入图片描述

Deque使用

当成单端队列使用

常用方法解释
offerLast(e)队列头添加元素,成功为true,失败为false
pollFirst ()返回队列头,出队列,队列空为null
peekFirst()返回队列头,不出队列,队列空为null

当成双端队列使用

常用方法解释
offerFirst(e)队列头添加元素,成功为true,失败为false
pollFirst ()返回队列头,出队列,队列空为null
peekFirst()返回队列头,不出队列,队列空为null
offerLast(e)队列尾添加元素,成功为true,失败为false
pollLast()返回队列尾,出队列,队列空为null
peekLast()返回队列尾,不出队列,队列空为null

当成栈使用

方法解释
push(e)入栈,失败则抛出 illegalStateException
peek()返回栈顶值,失败抛出NoSuchElementException
pop()出栈,返回栈顶值,失败抛出NoSuchElementException

ArrayDeque的介绍

Deque接口的可调整大小的数组实现

  • 没有容量限制,按需增长
  • 非线程安全
  • 禁止null值
  • 当成栈使用时,比Stack类快
  • 当成单边队列使用时,比LinkedList快

底层是一个object数组,初始容量为8。head和tail属性控制队列头和队列尾。

transient Object[] elements; // non-private to simplify nested class access
   /**
     * The index of the element at the head of the deque (which is the
     * element that would be removed by remove() or pop()); or an
     * arbitrary number equal to tail if the deque is empty.
     */
    transient int head;

    /**
     * The index at which the next element would be added to the tail
     * of the deque (via addLast(E), add(E), or push(E)).
     */
    transient int tail;

    /**
     * The minimum capacity that we'll use for a newly created deque.
     * Must be a power of 2.
     */
    private static final int MIN_INITIAL_CAPACITY = 8;

在这里插入图片描述

ArrayDeque的使用

调用Deque接口中的方法即可

LinkedList的介绍

实现了List和Deque接口的双端链表实现类。接受null值。线程非安全。

在这里插入图片描述

核心结构是内部类Node

  private static class Node<E> {
        E item;
        Node<E> next;
        Node<E> prev;

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

LinkedList的使用

调用deque或者List中的接口方法即可使用。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值