马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
在刷力扣的时间,在举行二叉树的标题练习时,必要用队列来存储二叉树的结点。由于使用ArrayDeque实现Deque风俗了,以是默认使用ArrayDeque来实现Deque。- Deque<TreeNode> dq=new ArrayDeque<>();
复制代码 但是在运行的时间,发现这个dq中无法存入null空结点,会报空指针非常。于是实验了使用LinkedList来实现Deque。- Deque<TreeNode> dq=new LinkedList<>();
复制代码 如许再将null空结点存入这个队列就不会报错了,我分别检察了一下两者的源码。他们的源码分别如下:- //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);
- }
复制代码- //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不会。详细缘故原由我也不清晰。。
|