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

相关推荐
揽昕4 分钟前
判断对象是否含有某个属性
开发语言·前端·javascript
思成Codes6 分钟前
ACM训练:接雨水3.0——动态接雨水
数据结构·算法
alphaTao6 分钟前
LeetCode 每日一题 2026/1/12-2026/1/18
python·算法·leetcode
sin_hielo8 分钟前
leetcode 2943
数据结构·算法·leetcode
phltxy22 分钟前
解锁JavaScript WebAPI:从基础到实战,打造交互式网页
开发语言·javascript
资生算法程序员_畅想家_剑魔24 分钟前
Java常见技术分享-分布式篇-分布式系统基础理论
java·开发语言·分布式
Snow_day.1 小时前
有关平衡树
数据结构·算法·贪心算法·动态规划·图论
FL16238631291 小时前
C# winform部署yolo26-obb旋转框检测的onnx模型演示源码+模型+说明
开发语言·c#
色空大师1 小时前
【Result<T>泛型接收转化失败】
java·泛型
Hcoco_me1 小时前
大模型面试题75:讲解一下GRPO的数据回放
人工智能·深度学习·算法·机器学习·vllm