Java Creating ArrayDeque

Java Creating ArrayDeque

An ArrayDeque is a resizable array implementation of the Deque interface in Java. It allows you to store a collection of elements in a double-ended queue, which means that you can add or remove elements from either the front or the back of the queue.

Here is an example of how to create an ArrayDeque in Java:

import java.util.ArrayDeque;

public class Main {
  public static void main(String[] args) {
    // Create an ArrayDeque
    ArrayDeque<String> queue = new ArrayDeque<>();

    // Add elements to the ArrayDeque
    queue.add("Apple");
    queue.add("Banana");
    queue.add("Cherry");
    queue.add("Date");
    queue.add("Elderberry");

    // Print the ArrayDeque
    System.out.println(queue);  // Output: [Apple, Banana, Cherry, Date, Elderberry]
  }
}
Source:ww‮l.w‬autturi.com

In this example, we create an ArrayDeque of type String and add some elements to it. The ArrayDeque stores the elements in the order in which they were added.

You can also create an ArrayDeque with an initial capacity, which specifies the number of elements the ArrayDeque can hold before it needs to resize itself. Here is an example:

import java.util.ArrayDeque;

public class Main {
  public static void main(String[] args) {
    // Create an ArrayDeque with an initial capacity of 10
    ArrayDeque<String> queue = new ArrayDeque<>(10);

    // Add elements to the ArrayDeque
    queue.add("Apple");
    queue.add("Banana");
    queue.add("Cherry");
    queue.add("Date");
    queue.add("Elderberry");

    // Print the ArrayDeque
    System.out.println(queue);  // Output: [Apple, Banana, Cherry, Date, Elderberry]
  }
}

In this example, we create an ArrayDeque with an initial capacity of 10. The ArrayDeque will allocate an array with a size of 10 to store the elements, which can help improve performance if you know that the ArrayDeque will contain a large number of elements.

You can use the various methods of the ArrayDeque class to add or remove elements from the front or the back of the queue, or to retrieve elements from the queue without removing them. For example, you can use the addFirst and addLast methods to add elements to the front or the back of the queue, respectively, or you can use the pollFirst and pollLast methods to remove elements from the front or the back of the queue, respectively.

Created Time:2017-11-03 00:14:39  Author:lautturi