ArrayDeque is a data structure that implements the Deque interface. Deque is the short form of "double ended queue" and generally pronounced as "deck". The ArrayDeque does not limit the number of its elements. It can grow when needed. It is likely to be faster than stack or queue data structure when it used as stack or queue data structure. Most its methods (e.g. add, addFirst, addLast, clear, clone, getFirst, getLast, isEmpty, peekFirst, peakLas, pollFirst, pollLast, size, and toArray) of the ArrayDeque run in constant time (c) and few methods (e.g. remove, removeFirstOccurence, removeLastOccurrence, and contains) run in linear time (O(n)). You can create an ArrayDeque object by using one of the ArrayDeque constructors.
-ArrayDeque() creates an empty deque enough for storing 16 elements.
-ArrayDeque(Collection<? extends E> c) creates a deque from a specified collection object (e.g. ArrayDeque, LinkedList, Stack, ...).
-ArrayDeque(int capacity) creates an empty deque with initial capacity (number of elements).
To add a new element to the ArrayDeque object, you can use the add(E e), addFirst(E e), and addLast(E e) methods. The add and addLast method will add the element at the end of the deque. The addFirst method will add the element to the front of the deque.
ArrayDeque<Integer> ad=new ArrayDeque<Integer>();
Random random=new Random();
To remove elements from the ArrayDeque object, you will use the clear, poll, pollFirst, pollLast, remove, remove(Object o), removeFirst(), removeFirstOccurence(Object o), removeLast, and removeLastOccurrence (Object o). The clear method will remove all elements of the deque. The poll, pollFirst, remove, removeFirst methods will retrieve and remove the first element of the deque. The pollLast and removeLast method will retrieve and remove the last elelement of the deque. If you want to remove any element in the deque, you can use the remove(Object o) method. The removeFirstOccurrence will remove the the first matched element and the removeLastOccurrence will remove the last matched elements.
If you want to get the elements without removing them from the deque, you will use the getFirst, getLast, peekFirst, and peekLast methods. The getFirst and peekFirst methods return the first element of the deque. In contrast, the getLast and peekLast methods return the last element of the deque.
System.out.println("The first element is "+fele+".");
System.out.println("The last element is "+lele+".");
Another useful method of the ArrayDeque is iterator(). The iterator method can be used traverse through the deque. See the example code below.