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

相关推荐
leoufung几秒前
103. 二叉树的锯齿形层序遍历(LeetCode 103)
算法·leetcode·职场和发展
程序员东岸几秒前
《数据结构——排序(上)》从扑克牌到分治法:插入排序与希尔排序的深度剖析
数据结构·笔记·算法·排序算法
Mr.朱鹏3 分钟前
RocketMQ可视化监控与管理
java·spring boot·spring·spring cloud·maven·intellij-idea·rocketmq
带刺的坐椅6 分钟前
Solon AI 开发学习9 - chat - 聊天会话(对话)的记忆与持久化
java·ai·llm·openai·solon·mcp
曹牧6 分钟前
Oracle中ROW_NUMBER() OVER()
java·数据库·sql
客梦8 分钟前
数据结构-哈希表
java·数据结构·笔记
Yolo566Q9 分钟前
基于ArcGIS、InVEST与RUSLE水土流失模拟及分析
开发语言·python
草原印象10 分钟前
Spring SpringMVC Mybatis框架整合实战
java·spring·mybatis·spring mvc
八个程序员10 分钟前
c++——探讨a÷b(long long)
开发语言·c++
四谎真好看14 分钟前
Java 黑马程序员学习笔记(进阶篇30)
java·笔记·学习·学习笔记