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

相关推荐
MediaTea3 分钟前
AI 术语通俗词典:ID3 算法
人工智能·算法
Morwit4 分钟前
【力扣hot100】 221. 最大正方形
前端·算法·leetcode
Javatutouhouduan6 分钟前
大厂Java岗最新面试真题汇总!
java·java面试·后端开发·java编程·java程序员·互联网大厂·java八股文
逻辑驱动的ken7 分钟前
Java高频面试考点场景题23
java·开发语言·数据库·面试·职场和发展·哈希算法
xxjj998a14 分钟前
PHP vs Java:核心区别与应用场景全解析
java·开发语言·php
呃呃本18 分钟前
算法题(矩阵)
线性代数·算法·矩阵
2301_7890156219 分钟前
Linux基础指令(一)
linux·运维·服务器·c语言·开发语言·c++·linux指令
csgo打的菜又爱玩26 分钟前
11.JobManager 启动流程总结
大数据·开发语言·qt·microsoft·flink
呃呃本28 分钟前
算法题(普通数组、矩阵)
线性代数·算法·矩阵
用户2986985301429 分钟前
Java 从零生成 Word 文档:段落、图片与表格操作
java·后端