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

相关推荐
程序员-King.9 分钟前
day143—递归—对称二叉树(LeetCode-101)
数据结构·算法·leetcode·二叉树·递归
BlockChain88810 分钟前
字符串最后一个单词的长度
算法·go
爱吃泡芙的小白白12 分钟前
深入解析:2024年AI大模型核心算法与应用全景
人工智能·算法·大模型算法
XXOOXRT38 分钟前
基于SpringBoot的加法计算器
java·spring boot·后端·html5
阿崽meitoufa42 分钟前
JVM虚拟机:垃圾收集器和判断对象是否存活的算法
java·jvm·算法
yugi9878381 小时前
基于遗传算法优化主动悬架模糊控制的Matlab实现
开发语言·matlab
我是苏苏1 小时前
C#高级:使用ConcurrentQueue做一个简易进程内通信的消息队列
java·windows·c#
moxiaoran57532 小时前
Go语言的错误处理
开发语言·后端·golang
ballball~~2 小时前
拉普拉斯金字塔
算法·机器学习
Cemtery1162 小时前
Day26 常见的降维算法
人工智能·python·算法·机器学习