嗨,我使用 add 和 offer 在最后一步添加我的元素。两者都返回布尔值,并且除了 NPE 之外都不会抛出任何异常。
public class ArrayDequeDemo {
public static void main(String[] args) {
// Create ArrayDeque elements.
ArrayDeque<Integer> deque = new ArrayDeque<>();
deque.add(10);
deque.offer(30);
}
}
两者都将通过返回一个布尔值将元素添加到最后一个位置。
JAVA实现
//For Add and Offer Both
public void addLast(E e) {
if (e == null)
throw new NullPointerException();
elements[tail] = e;
if ( (tail = (tail + 1) & (elements.length - 1)) == head)
doubleCapacity();
}