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

相关推荐
kaikaile199515 分钟前
34节点配电网牛顿-拉夫逊潮流计算 + 分布式电源(DG)多场景分析的 MATLAB
开发语言·分布式·matlab
QT 小鲜肉16 分钟前
【C++基础与提高】第一章:走进C++的世界——从零开始的编程之旅
开发语言·c++·笔记·qt
java1234_小锋18 分钟前
MyBatis如何处理懒加载和预加载?
java·开发语言·mybatis
狮子也疯狂19 分钟前
基于Django实现的智慧校园考试系统-自动组卷算法实现
python·算法·django
@木辛梓24 分钟前
模版 c++
开发语言·c++
爱coding的橙子30 分钟前
每日算法刷题Day84:11.11:leetcode 动态规划9道题,用时2h
算法·leetcode·动态规划
oioihoii32 分钟前
C++中的线程同步机制浅析
开发语言·c++
hdsoft_huge36 分钟前
小程序弱网 / 无网场景下 CacheManager 离线表单与拍照上传解决方案
java·小程序·uni-app
麦嘟学编程43 分钟前
开发环境搭建之JDK11+maven3.9.8+tomcat9安装
java
小坏讲微服务44 分钟前
使用 Spring Cloud Gateway 实现集群
java·spring boot·分布式·后端·spring cloud·中间件·gateway