add 方法和 offer 方法 的区别是:
当队列的容量固定(有界)时, 使用offer 方法,如果插入不成功则返回 false值。而使用add 方法可能无法插入元素,只是抛出一个异常。
而remove() 和poll() 不同的地方是:
当队列为空时:remove() 方法和add的方法一样都会抛出一个异常,而 poll() 方法则返回 null值。 作者: 王超 时间: 2012-7-20 15:07
add是list的;offer是queue的
add:Inserts the specified element at the specified position in this list
将指定的元素插入到list中指定的的位置。
offer:Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions.
如果在不违反容量限制的情况下,尽可能快的将指定的元素插入到queue中去
public boolean offer(E e) {
return add(e);
}
从源码中可以看到
其实add和offer没什么区别,offer底层也是调用的add方法
--------------------------------
public E remove() {
return removeFirst();
}
public E removeFirst() {
return remove(header.next);
}
public E next() {
checkForComodification();
if (nextIndex == size)
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.element;
}
public E poll() {
if (size==0)
return null;
return removeFirst();
}
有源码看出:
当链表为空时,poll返回null,remove会抛出异常
作者: 石好强 时间: 2012-7-20 15:53
看了本篇回复,我惊了。高手这么多,新特性,新接口,源码都出来了!就是一个区别么,都让你们说了,我还说啥...
赶快回去啃笔记去了...作者: 陈雷 时间: 2012-7-20 15:54
add 方法在插入失败的时候会抛出 IllegalStateException 异常
而offer可以通过返回值来判断成功与否作者: 张凯 时间: 2012-7-20 16:25
add方法与offer方法的不同之处是:
你看:
boolean offer(E e)
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. When using a capacity-restricted queue, this method is generally preferable to add(E), which can fail to insert an element only by throwing an exception.