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

相关推荐
码界索隆8 小时前
Python转Java系列:前言
java·开发语言·python
蓦然回首却已人去楼空8 小时前
【分词:中文分词】BPE字节级分词算法实现汉字表达!
java·算法·中文分词
3DVisionary8 小时前
aero-engine-blade-thermal-fatigue-dic-inspection
人工智能·算法·机器学习·航空发动机·高温dic·涡轮叶片·热疲劳
asdfg12589638 小时前
一文理解Java中的泛型
java·开发语言
飞翔中文网8 小时前
Java学习笔记之反射
java·笔记·学习
河阿里8 小时前
Spring Boot:整合Quartz集群部署指南
java·spring boot·后端
Kurisu5759 小时前
深度拆解:从二进制切片到并发控制,大文件断点续传的底层工程设计
算法
Hiter_John9 小时前
Golang的变量常量初始化
开发语言·后端·golang
小肥君9 小时前
gpu安装milvus问题解决
java·eureka·milvus
砍材农夫9 小时前
物联网实战:Spring Boot MQTT | 模拟器Paho客户端拆解高性能
java·javascript·spring boot·后端·物联网·struts