java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to create Deque using ArrayDeque class?

This example show you how to create a Deque using the ArrayDeque implementation. The ArrayDeque stores its elements using an array. If the number of elements exceeds the space in the array, a new array will be allocated, and all elements moved the the new allocated array.

In the code below we initiate the size of the Deque to store five elements. When we add the element number six the array that stores the elements of the Deque will be resized.

package com.javacoderanch.example.util;

import java.util.ArrayDeque;
import java.util.Deque;

public class ArrayDequeDemo {
    public static void main(String[] args) {
        //
        // Constructs an empty array deque with an initial capacity
        // sufficient to hold the specified number of elements.
        //
        Deque<Integer> deque = new ArrayDeque<Integer>(5);
        deque.add(1);
        deque.add(1);
        deque.add(2);
        deque.add(3);
        deque.add(5);        
        deque.add(8);
        deque.add(14);
        deque.add(22);

        for (Integer number : deque) {
            System.out.println("Number = " + number);
        }
    }
}