Java Utility Library

Java ArrayDeque - toArray() Method



The java.util.ArrayDeque.toArray() method returns an array containing all of the elements in the deque in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the given deque fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of the given deque.

If the deque fits in the specified array with room to spare, the element in the array immediately following the end of the deque is set to null.

Syntax

public <T> T[] toArray(T[] a)

Parameters

a Specify the array into which the elements of the ArrayDeque are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

Return Value

Returns an array containing all elements of the deque.

Exception

  • Throws ArrayStoreException, if the runtime type of a is not a supertype of the runtime type of every element in the deque.
  • Throws NullPointerException, if the given array is null.

Example:

In the example below, the java.util.ArrayDeque.toArray() method returns an array containing all elements of the given deque.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an ArrayDeque
    ArrayDeque<Integer> MyDeque = new ArrayDeque<Integer>();

    //populating ArrayDeque
    MyDeque.add(10);
    MyDeque.add(20);
    MyDeque.add(30);
    MyDeque.add(40);

    //creating an empty array
    Integer[] Arr = new Integer[5];

    //convert the deque into an array
    MyDeque.toArray(Arr);

    //print the array
    System.out.print("The Arr contains: ");
    for(int i = 0; i < Arr.length; i++)
      System.out.print(Arr[i]+ " ");
  }
}

The output of the above code will be:

The Arr contains: 10 20 30 40 null

❮ Java.util - ArrayDeque