欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > JAVA中的ArrayDeque和LinkedList实现Deque,前者不能存NULL结点,后者可以存放NULL。

JAVA中的ArrayDeque和LinkedList实现Deque,前者不能存NULL结点,后者可以存放NULL。

2024/10/24 19:27:28 来源:https://blog.csdn.net/qq_52983535/article/details/141157732  浏览:    关键词:JAVA中的ArrayDeque和LinkedList实现Deque,前者不能存NULL结点,后者可以存放NULL。

在刷力扣的时候,在进行二叉树的题目训练时,需要用队列来存储二叉树的结点。因为使用ArrayDeque实现Deque习惯了,所以默认使用ArrayDeque来实现Deque。

Deque<TreeNode> dq=new ArrayDeque<>();

但是在运行的时候,发现这个dq中无法存入null空结点,会报空指针异常。于是尝试了使用LinkedList来实现Deque。

Deque<TreeNode> dq=new LinkedList<>();

这样再将null空结点存入这个队列就不会报错了,我分别查看了一下两者的源码。他们的源码分别如下:

    //ArrayDequepublic 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);}
    //LinkedListpublic 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不会。具体原因我也不清楚。。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com