先说结论:
pop()和element()在该队列为空时会抛出NoSuchElementException()异常
poll()与peek()在该队列为空时return null;
Deque(双端队列)中的element()与peek()
二者都是检索该队列中首元素,那么二者的区别在哪呢?
public E element() {
return getFirst();
}
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
pop()与poll()的区别
同理,让我们先看一下源码:
pop()方法的底层实现
public E pop() {
return this.removeFirst();
}
public E removeFirst() {
LinkedList.Node var1 = this.first;
if (var1 == null) {
throw new NoSuchElementException();
} else {
return this.unlinkFirst(var1);
}
}
poll()方法的底层实现
public E poll() {
LinkedList.Node var1 = this.first;
return var1 == null ? null : this.unlinkFirst(var1);
}
二者最终都调用这个方法:unlinkFirst() 即:都会将该元素从队列中删除
private E unlinkFirst(LinkedList.Node<E> var1) {
Object var2 = var1.item;
LinkedList.Node var3 = var1.next;
var1.item = null;
var1.next = null;
this.first = var3;
if (var3 == null) {
this.last = null;
} else {
var3.prev = null;
}
--this.size;
++this.modCount;
return var2;
}
相信大家也看出来了,二者的区别与上面那俩组合一样
总结:
- pop()方法因为在底层调用了removeFirst()方法,在deque为空时会抛出NoSuchElementException()异常
- element()方法因为在底层调用了getFirst()方法,在deque为空时会抛出NoSuchElementException()异常
- poll()方法在deque为空时return null;
- peek()方法在deque为空时return null;