ArrayDeque.toArray(E[]): This method is available in java.util.ArrayDeque class of Java.
Syntax:
<E> E[] java.util.ArrayDeque.toArray(E[] a)
This method takes one argument. This method returns an array containing all of the elements in this deque in proper sequence.
Parameters: One parameter is required for this method.
a: the array into which the elements of the deque are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
Returns: an array containing all of the elements in this deque.
Throws:
1. ArrayStoreException - if the runtime type of the specified array is not a supertype of the runtime type of every element in this deque.
2. NullPointerException - if the specified array is null
Approach 1: When no exception
Java
import java.util.ArrayDeque;import java.util.Arrays;public class ArrayDequetoArray2 {public static void main(String[] args) {ArrayDeque<Integer> arrayDeque =new ArrayDeque<Integer>();arrayDeque.add(1);arrayDeque.add(4);arrayDeque.add(7781);arrayDeque.add(478);arrayDeque.add(118);arrayDeque.add(99);Integer list2[] = new Integer[5];list2 = arrayDeque.toArray(list2);System.out.println(Arrays.toString(list2));}}
Output:
[1, 4, 7781, 478, 118, 99]
Approach 2: ArrayStoreException
Java
import java.util.ArrayDeque;import java.util.Arrays;public class ArrayDequetoArray2 {public static void main(String[] args) {ArrayDeque<Integer> arrayDeque =new ArrayDeque<Integer>();arrayDeque.add(1);arrayDeque.add(4);arrayDeque.add(7781);arrayDeque.add(478);arrayDeque.add(118);arrayDeque.add(99);Long list2[] = new Long[5];list2 = arrayDeque.toArray(list2);System.out.println(Arrays.toString(list2));}}
Output:
Exception in thread "main" java.lang.ArrayStoreException: arraycopy: element type mismatch: can not cast one of the elements of java.lang.Object[] to the type of the destination array, java.lang.Long at java.base/java.lang.System.arraycopy(Native Method) at java.base/java.util.Arrays.copyOfRange(Arrays.java:3786) at java.base/java.util.ArrayDeque.toArray(ArrayDeque.java:1079) at java.base/java.util.ArrayDeque.toArray(ArrayDeque.java:1130)
Approach 3: NullPointerException
Java
import java.util.ArrayDeque;import java.util.Arrays;public class ArrayDequetoArray2 {public static void main(String[] args) {ArrayDeque<Integer> arrayDeque = null;Integer list2[] = new Integer[5];list2 = arrayDeque.toArray(list2);System.out.println(Arrays.toString(list2));}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.ArrayDeque.toArray(Object[])" because "arrayDeque" is null
No comments:
Post a Comment