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

相关推荐
swordbob13 小时前
缓存延迟双删的两种策略
java·缓存
凡人叶枫13 小时前
Effective C++ 条款08:别让异常逃离析构函数
java·linux·数据库·c++·嵌入式开发
云烟成雨TD14 小时前
Agent Scope Java 2.x 系列【4】模型层
java·人工智能·agent
云淡风轻~窗明几净14 小时前
角谷猜想的任意算法测试
数据结构·人工智能·算法
qq_4221525714 小时前
Word 文件太大怎么压缩?2026 年文档瘦身方案对比
开发语言·c#·word
云烟成雨TD14 小时前
Agent Scope Java 2.x 系列【5】智能体抽象层
java·人工智能·agent
happygrilclh14 小时前
赚外快了:等离子表面处理机电源算法需求说明
算法
charliedev14 小时前
Jedi:Python 自动补全与静态分析的实用工具
开发语言·python·其他
阿伟AI说14 小时前
Codex 桌面版接入国产模型系列二:Codex++
java·开源软件·ai编程·腾讯云ai代码助手
ji1985944314 小时前
MATLAB 求散点曲线斜率
开发语言·算法·matlab