ArrayDeque Class

ArrayDeque class extends AbstractCollection and implements the Deque interface.

ArrayDeque creates a dynamic array and has no capacity restrictions. ArrayDeque is a generic class that has this declaration:

class ArrayDeque<E>

E specifies the type of objects stored in the collection.

ArrayDeque defines the following constructors:

ArrayDeque( )
builds an empty deque. starting capacity is 16.
ArrayDeque(int size)
builds a deque that has the specified initial capacity.
ArrayDeque(Collection<? extends E> c)
creates a deque that is initialized with the elements of the collection passed in c.

The following program demonstrates ArrayDeque by using it to create a stack:

 
import java.util.ArrayDeque;

public class Main {
  public static void main(String args[]) {
    ArrayDeque<String> adq = new ArrayDeque<String>();
    adq.push("A");
    adq.push("B");
    adq.push("D");
    adq.push("E");
    adq.push("F");
    while (adq.peek() != null){
      System.out.println(adq.pop() + " ");      
    }
  }
}
  

The following code uses an array deque as a stack

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

public class Main {
  public static void main(String[] args) {
    Deque<String> stack = new ArrayDeque<String>();
    String[] weekdays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
    for (String weekday : weekdays){
      stack.push(weekday);
    }
      
    while (stack.peek() != null){
      System.out.println(stack.pop());
    }
      
  }
}
  

Saturday
Friday
Thursday
Wednesday
Tuesday
Monday
Sunday
 
import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
  public static void main(String[] args) {
    MyDequeue stack = new MyDequeue();
    for (int i = 0; i < 5; i++) {
      stack.push(i);
    }
    System.out.println("After pushing 5 elements: " + stack);

    int m = stack.pop();
    System.out.println("Popped element = " + m);

    System.out.println("After popping 1 element : " + stack);

    int n = stack.peek();
    System.out.println("Peeked element = " + n);
    System.out.println("After peeking 1 element : " + stack);
  }
}

class MyDequeue {
  private Deque<Integer> data = new ArrayDeque<Integer>();

  public void push(Integer element) {
    data.addFirst(element);
  }

  public Integer pop() {
    return data.removeFirst();
  }

  public Integer peek() {
    return data.peekFirst();
  }

  public String toString() {
    return data.toString();
  }

}
  
Home 
  Java Book 
    Collection