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

相关推荐
西京刀客几秒前
构建 Go 可执行文件镜像 | 探索轻量级 Docker 基础镜像(我应该选择哪个 Docker 镜像?)
开发语言·docker·golang
然我22 分钟前
链表指针玩不转?从基础到双指针,JS 实战带你破局
前端·数据结构·算法
没有羊的王K28 分钟前
SSM框架学习DI入门——day2
java·spring boot·学习
公子绝28 分钟前
JAVA学习笔记 使用notepad++开发JAVA-003
java·学习·notepad++·java开发环境
EndingCoder30 分钟前
算法与前端的可访问性
前端·算法·递归·树形结构
似璟如你36 分钟前
Java开发八股文之基础篇+spring+集合
java·开发语言·面试
本杰明15238 分钟前
2025/7/14——java学习总结
java·开发语言·学习
2345VOR43 分钟前
【C#地图显示教程:实现鼠标绘制图形操作】
开发语言·c#·计算机外设·地图显示鼠标交互
开开心心_Every1 小时前
可增添功能的鼠标右键优化工具
开发语言·pdf·c#·计算机外设·电脑·音视频·symfony
星释1 小时前
优雅的Java:01.数据更新如何更优雅
java·开发语言·spring boot