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

相关推荐
荒夜长歌1 分钟前
传统java行业跳槽面试汇总(后续会更新)
java·面试·跳槽
旷世奇才李先生2 分钟前
065智慧农业专家远程指导系统-springboot+vue
java·vue.js·spring boot
大迪deblog2 分钟前
系统架构设计-软件架构风格
java·开发语言·架构·软件构建
盐水冰3 分钟前
【烘焙坊项目】后端搭建(10) - 地址簿功能&用户下单&微信支付
java·数据库·后端
csbysj20204 分钟前
Bootstrap 弹出框
开发语言
重庆小透明6 分钟前
【面试问题】java小厂
java·开发语言·面试
smj2302_7968265214 分钟前
解决leetcode第3869题.统计区间内奇妙数的数目
python·算法·leetcode
CodeCraft Studio16 分钟前
Parasoft C/C++嵌入式软件测试解决方案:安全、可靠且符合标准
开发语言·c++·安全·单元测试·代码规范·parasoft·嵌入式软件测试
xindon1220 分钟前
如何集成单点登录和设计子系统的权限管理三
java
TracyCoder12329 分钟前
LeetCode Hot100(66/100)——118. 杨辉三角
算法·leetcode·职场和发展