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

相关推荐
村口曹大爷3 分钟前
JDK 24 正式发布:性能压轴,为下一代 LTS 铺平道路
java·开发语言
1.14(java)6 分钟前
MySQL数据库操作全攻略
java·数据库·mysql
副露のmagic7 分钟前
更弱智的算法学习 day13
学习·算法
正远数智26 分钟前
深度解析:SRM系统如何赋能采购库存协同
java·lowcode
青岛少儿编程-王老师29 分钟前
CCF编程能力等级认证GESP—C++1级—20251227
java·c++·算法
Sylus_sui38 分钟前
git中如何从某次历史提交节点上创建一个新的分支
git·算法·哈希算法
nn在炼金1 小时前
大模型领域负载均衡技术
人工智能·算法·负载均衡
ysdysyn1 小时前
C# Modbus RTU 多从站控制全攻略:一端口,双轴控制
开发语言·c#·mvvm·通讯·modbus rtu
hashiqimiya1 小时前
java程序的并发
java·开发语言·python
微露清风1 小时前
系统性学习C++进阶-第十四讲-二叉搜索树
开发语言·c++·学习