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

[复制链接]
发表于 2026-2-6 19:58:54 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
在刷力扣的时间,在举行二叉树的标题练习时,必要用队列来存储二叉树的结点。由于使用ArrayDeque实现Deque风俗了,以是默认使用ArrayDeque来实现Deque。
  1. Deque<TreeNode> dq=new ArrayDeque<>();
复制代码
但是在运行的时间,发现这个dq中无法存入null空结点,会报空指针非常。于是实验了使用LinkedList来实现Deque。
  1. Deque<TreeNode> dq=new LinkedList<>();
复制代码
如许再将null空结点存入这个队列就不会报错了,我分别检察了一下两者的源码。他们的源码分别如下:
  1.     //ArrayDeque
  2.     public void addFirst(E e) {
  3.         if (e == null)
  4.             throw new NullPointerException();
  5.         final Object[] es = elements;
  6.         es[head = dec(head, es.length)] = e;
  7.         if (head == tail)
  8.             grow(1);
  9.     }
  10.     /**
  11.      * Inserts the specified element at the end of this deque.
  12.      *
  13.      * <p>This method is equivalent to {@link #add}.
  14.      *
  15.      * @param e the element to add
  16.      * @throws NullPointerException if the specified element is null
  17.      */
  18.     public void addLast(E e) {
  19.         if (e == null)
  20.             throw new NullPointerException();
  21.         final Object[] es = elements;
  22.         es[tail] = e;
  23.         if (head == (tail = inc(tail, es.length)))
  24.             grow(1);
  25.     }
复制代码
  1.     //LinkedList
  2.     public void addFirst(E e) {
  3.         linkFirst(e);
  4.     }
  5.     /**
  6.      * Appends the specified element to the end of this list.
  7.      *
  8.      * <p>This method is equivalent to {@link #add}.
  9.      *
  10.      * @param e the element to add
  11.      */
  12.     public void addLast(E e) {
  13.         linkLast(e);
  14.     }
复制代码
可以看到在ArrayDeque会对参加的值举行判定,假如为空就会报出非常,而LinkedList不会。详细缘故原由我也不清晰。。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表