Close

Java Collections - ArrayDeque.toArray() Examples

Java Collections Java Java API 


Class:

java.util.ArrayDeque

java.lang.Objectjava.lang.Objectjava.util.AbstractCollectionjava.util.AbstractCollectionjava.util.CollectionCollectionjava.util.ArrayDequejava.util.ArrayDequejava.util.DequeDequejava.lang.CloneableCloneablejava.io.SerializableSerializableLogicBig

Methods:

public Object[] toArray()

Returns an array containing all of the elements in this deque in proper sequence (from first to last element).

The returned array will be "safe" in that no references to it are maintained by this deque. (In other words, this method must allocate a new array). The caller is thus free to modify the returned array.



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

Returns an array containing all of the elements in this deque in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the 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 this deque.

If this deque fits in the specified array with room to spare (i.e., the array has more elements than this deque), the element in the array immediately following the end of the deque is set to null .


Examples


package com.logicbig.example.arraydeque;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class ToArrayExample {

public static void main(String... args) {
ArrayDeque<Integer> ad = new ArrayDeque<>(List.of(3, 8, 1, 9));
System.out.println(ad);
Object[] objects = ad.toArray();
System.out.println(Arrays.toString(objects));
}
}

Output

[3, 8, 1, 9]
[3, 8, 1, 9]




package com.logicbig.example.arraydeque;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.List;

public class ToArrayExample2 {

public static void main(String... args) {
ArrayDeque<Integer> ad = new ArrayDeque<>(List.of(3, 8, 1, 9));
System.out.println(ad);
Integer[] integers = ad.toArray(new Integer[ad.size()]);
System.out.println(Arrays.toString(integers));
}
}

Output

[3, 8, 1, 9]
[3, 8, 1, 9]




package com.logicbig.example.arraydeque;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.List;

public class ToArrayExample3 {

public static void main(String... args) {
ArrayDeque<Integer> ad = new ArrayDeque<>(List.of(3, 8, 1, 9));
System.out.println(ad);
Integer[] integers = ad.toArray(new Integer[ad.size() + 3]);
System.out.println(Arrays.toString(integers));
}
}

Output

[3, 8, 1, 9]
[3, 8, 1, 9, null, null, null]




See Also