JAVA中的ArrayDeque和LinkedList实现Deque,前者不能存NULL结点,后者可以存放NULL。

在刷力扣的时候,在进行二叉树的题目训练时,需要用队列来存储二叉树的结点。因为使用ArrayDeque实现Deque习惯了,所以默认使用ArrayDeque来实现Deque。

java 复制代码
Deque<TreeNode> dq=new ArrayDeque<>();

但是在运行的时候,发现这个dq中无法存入null空结点,会报空指针异常。于是尝试了使用LinkedList来实现Deque。

java 复制代码
Deque<TreeNode> dq=new LinkedList<>();

这样再将null空结点存入这个队列就不会报错了,我分别查看了一下两者的源码。他们的源码分别如下:

java 复制代码
    //ArrayDeque
    public void addFirst(E e) {
        if (e == null)
            throw new NullPointerException();
        final Object[] es = elements;
        es[head = dec(head, es.length)] = e;
        if (head == tail)
            grow(1);
    }

    /**
     * Inserts the specified element at the end of this deque.
     *
     * <p>This method is equivalent to {@link #add}.
     *
     * @param e the element to add
     * @throws NullPointerException if the specified element is null
     */
    public void addLast(E e) {
        if (e == null)
            throw new NullPointerException();
        final Object[] es = elements;
        es[tail] = e;
        if (head == (tail = inc(tail, es.length)))
            grow(1);
    }
java 复制代码
    //LinkedList
    public void addFirst(E e) {
        linkFirst(e);
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #add}.
     *
     * @param e the element to add
     */
    public void addLast(E e) {
        linkLast(e);
    }

可以看到在ArrayDeque会对加入的值进行判断,如果为空就会报出异常,而LinkedList不会。具体原因我也不清楚。。

相关推荐
渣哥4 分钟前
Kafka消息丢失的3种场景,生产环境千万要注意
java
渣哥4 分钟前
ElasticSearch深度分页的致命缺陷,千万数据查询秒变蜗牛
java
Olrookie5 分钟前
XXL-JOB GLUE模式动态数据源实践:Spring AOP + MyBatis 解耦多库查询
java·数据库·spring boot
zzz9337 分钟前
transformer实战——mask
算法
柯南二号22 分钟前
【Java后端】MyBatis-Plus 原理解析
java·开发语言·mybatis
又是努力搬砖的一年30 分钟前
SpringBoot中,接口加解密
java·spring boot·后端
:-)33 分钟前
idea配置maven国内镜像
java·ide·maven·intellij-idea
一只鱼^_35 分钟前
牛客周赛 Round 105
数据结构·c++·算法·均值算法·逻辑回归·动态规划·启发式算法
是阿建吖!36 分钟前
【动态规划】斐波那契数列模型
算法·动态规划
我是哈哈hh42 分钟前
【Node.js】ECMAScript标准 以及 npm安装
开发语言·前端·javascript·node.js