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

相关推荐
Huangxy__19 小时前
接口的的的~
java
廋到被风吹走19 小时前
【MySql】超时问题分析
java·数据库·mysql
云创智城-yuncitys19 小时前
[特殊字符]⚡ 停充一体化云平台:基于微服务架构的城市智慧停车+新能源充电解决方案
java·微服务·架构
csbysj202019 小时前
Python break 语句详解
开发语言
毕设源码-朱学姐19 小时前
【开题答辩全过程】以 高效便捷的民航订票系统为例,包含答辩的问题和答案
java
2401_8579182919 小时前
C++中的访问者模式实战
开发语言·c++·算法
格林威19 小时前
工业相机图像高速存储(C++版):RAID 0 NVMe SSD 阵列暴力提速,附海康实战代码!
开发语言·c++·人工智能·数码相机·计算机视觉·工业相机·堡盟相机
零雲19 小时前
java面试:Spring事务失效的场景有哪些?
java·数据库·面试
二月十六19 小时前
运行 ‘XXXX‘ 时出错 运行 XXXX时出错。命令行过长。 通过 JAR 清单或通过类路径文件缩短命令行,然后重新运行。
java·jar
elseif12319 小时前
CSP-S提高级大纲
开发语言·数据结构·c++·笔记·算法·大纲·考纲