Understanding ArrayDeque class in java
ArrayDeque class
ArrayDeque is a resizable array implementation of the Deque interface.
It creates a dynamic array and has no size restriction.
ArrayDeque class extends AbstractCollection and implements the Deque interface.
Constructors of ArrayDeque class
Here are the constructors of the ArrayDeque class:
ArrayDeque()
Creates an empty array deque with initial capacity to hold 16 elements.
ArrayDeque(int numElements)
Creates an empty array deque with initial capacity as provided.
ArrayDeque(Collection c)
Creates array deque with elements of specified collection, in order of return of the collection’s iterator
ArrayDeque common methods
ArrayDeque has no methods of its own.
Here are the frequently used methods with ArrayDeque:
add(E e), offer(E e), addLast(E e), offerLast(E e)
Inserts the specified element at the end of this deque.
addFirst(E e), offerFirst(E e), push(E e)
Inserts the specified element at the front of this deque.
peek(), peekFirst()
Retieves, but does not remove the first element of the deque
pop(), removeFirst()
Retrieves and removes the first element of this deque.
remove(Object o)
Removes a single instance of the specified element from this deque. If the deque does not contain the element, it is unchanged.
remove()
Retrieves and removes first element from deque.
This method differs from poll only in that it throws an exception if this deque is empty.
poll()
Retrieves and removes first element from deque.
Returns NULL if deque is empty.
Example of using ArrayDeque class
Here is an example of ArrayDeque class and its methods.
package com.topjavatutorial; import java.util.ArrayDeque; public class ArrayDequeDemo { public static void main(String[] args) { ArrayDeque<String> adq = new ArrayDeque<String>(); adq.add("C"); // adds C adq.push("B"); // adds B at front of deque adq.addFirst("A"); // adds A at front of deque adq.offer("D"); // adds D at end of queue //adq at this point = [A, B, C, D] System.out.print(adq.remove()); // removes A from top and returns it System.out.print(adq.poll()); // removes B from top and returns it while(adq.peek() != null) System.out.print(adq.pop()); // removes element from top and returns it } }
In this program, we add the Strings [A, B, C, D] to the ArrayDeque using methods add(), push(), addFirst() and offer().
Then, these elements are removed and returned using remove(), poll(), pop() methods.
Running this program will output :
A B C D
You may also like following articles on Java Collections:
- ConcurrentHashMap in Java
- TreeMap in java
- LinkedHashMap in java
- WeakHashMap in java
- IdentityHashMap in java
- HashMap in java
- HashSet in java
- LinkedList in java
- ArrayList in java
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post
3 Responses
[…] ArrayDeque in java […]
[…] ArrayDeque in java […]
[…] ArrayDeque in java […]