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

相关推荐
程序员清风44 分钟前
阿里二面:Kafka 消费者消费消息慢(10 多分钟),会对 Kafka 有什么影响?
java·后端·面试
幼稚园的山代王44 分钟前
Prompt Enginering(提示工程)先进技术
java·人工智能·ai·chatgpt·langchain·prompt
dfsj6601144 分钟前
LLMs 系列科普文(14)
人工智能·深度学习·算法
周某某~1 小时前
二.单例模式‌
java·单例模式·设计模式
摸鱼仙人~1 小时前
深入理解Java单例模式:确保类只有一个实例
java·javascript·单例模式
SteveDraw1 小时前
C++动态链接库封装,供C#/C++ 等编程语言使用——C++动态链接库概述(总)
开发语言·c++·c#·封装·动态链接库
薛定谔的算法1 小时前
《盗梦空间》与JavaScript中的递归
算法
十五年专注C++开发1 小时前
设计模式之单例模式(二): 心得体会
开发语言·c++·单例模式·设计模式
hstar95271 小时前
三十五、面向对象底层逻辑-Spring MVC中AbstractXlsxStreamingView的设计
java·后端·spring·设计模式·架构·mvc
kaiaaaa1 小时前
算法训练第十一天
数据结构·算法