ArrayList.toArray(E[]) in Java

ArrayList.toArray(E[]): This method is available in java.util.ArrayList class of Java.

Syntax:

<E> E[] java.util.ArrayList.toArray(E[] a)

This method returns an array containing all of the elements in this list in proper sequence.

Parameters: One parameter is required for this method.

a: the array into which the elements of the list 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 the elements of the list.

Throws:

1. ArrayStoreException - if the runtime type of the specified array is not a super type of the runtime type of every element in this list.

2. NullPointerException - if the specified array is null

Approach 1: When no exception

Java

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListtoArray2 {
    public static void main(String[] args) {
        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);
        Integer list2[] = new Integer[arr.size()];
        list2 = arr.toArray(list2);

        System.out.println(Arrays.toString(list2));

    }
}

Output:

[1, 2, 3]


Approach 2: NullPointerException 

Java

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListtoArray2 {
    public static void main(String[] args) {
        ArrayList<Integer> arr = null;

        Integer list2[] = new Integer[5];
        list2 = arr.toArray(list2);

        System.out.println(Arrays.toString(list2));

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.ArrayList.toArray(Object[])" because "arr" is null



No comments:

Post a Comment