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不会。具体原因我也不清楚。。

相关推荐
该怎么办呢6 分钟前
基于cesium的三维不动产登记系统的设计与实现(毕业设计)
java·毕业设计
m0_748250037 分钟前
C++ 信号处理
c++·算法·信号处理
Ro Jace8 分钟前
电子侦察信号处理流程及常用算法
算法·信号处理
yuyanjingtao20 分钟前
动态规划 背包 之 凑钱
c++·算法·青少年编程·动态规划·gesp·csp-j/s
J不A秃V头A38 分钟前
多任务执行时,共享请求对象被并发修改
java
heartbeat..1 小时前
零基础学 SQL:DQL/DML/DDL/DCL 核心知识点汇总(附带连接云服务器数据库教程)
java·服务器·数据库·sql
编程武士1 小时前
Python 各版本主要变化速览
开发语言·python
hqwest1 小时前
码上通QT实战29--系统设置04-用户操作管理
开发语言·qt·模态窗体·addbindvalue·bindvalue
专注于大数据技术栈1 小时前
java学习--LinkedHashSet
java·开发语言·学习
这个图像胖嘟嘟1 小时前
前端开发的基本运行环境配置
开发语言·javascript·vue.js·react.js·typescript·npm·node.js