In Java, add(e) puts an element at the tail (the end) of an ArrayDeque and returns true. It does exactly what addLast(e) does; the only difference is that add reports success with a boolean, because it comes from the Collection and Queue interfaces.
Used as a queue, add is "join the back of the line". Elements come out of the head in the order they were added. Duplicates are allowed, so adding the same value twice stores it twice.
An instance method of java.util.ArrayDeque (Java 1.6+): a resizable-array deque with no capacity limit, no null elements, and no thread safety.
Syntax
Call add on the deque with the element to append.
Java
Deque<String> deque = new ArrayDeque<>();
boolean ok = deque.add("first"); // true, deque = [first]
deque.add("second"); // deque = [first, second]
Call
What it does
deque.add(e)
Appends e at the tail and returns true.
deque.addLast(e)
Same effect, but returns nothing (void).
deque.offer(e)
Same effect for ArrayDeque, also returns true.
deque.add(null)
Throws NullPointerException; nothing is added.
On a capacity-limited queue, add throws IllegalStateException when the queue is full. An ArrayDeque has no capacity limit, so for it that case never happens and add always returns true.
Library declarations
Java
// java.util.ArrayDeque<E>
public boolean add(E e)
// Declared in Collection<E>, Queue<E>, and Deque<E>
Parameters
Parameter
Description
e
Required. The element to add at the tail. Its type is the deque's element type E. Must not be null.
Return Value
Return Value
Description
boolean
Always true for an ArrayDeque, meaning the deque changed.
Throw or Return a Special Value?
Each end has a method that throws when it cannot work (such as on an empty deque) and one that returnsnull or false instead. The highlighted cell matches add().
One valid element.tasks starts with a single task, "write".
null is checked first.add(null) throws NullPointerException before anything is stored. The catch block prints the exception's simple class name.
Nothing changed. After the failed call the deque still prints [write] with size 1.
Why the rule exists. Methods like poll() and peek() return null to mean "empty". If null could be an element, that answer would be ambiguous.
Frequently Asked Questions
It appends the element at the tail (end) of the deque and returns true.
They put the element in the same place. add() returns a boolean (always true for ArrayDeque) and addLast() returns void.
No. ArrayDeque has no capacity limit, so add() always returns true. If it cannot add the element, it throws an exception instead.
No. add(null) throws NullPointerException. Use LinkedList if you really need null elements.
For ArrayDeque they behave the same. offer() is the usual choice in queue code because, on capacity-limited queues, it returns false instead of throwing.