Vector toArray(IntFunction) in Java

toArray(IntFunction): This method is available in java.util.Vector class of Java.

Syntax:

<K> K[] java.util.Collection.toArray(IntFunction<K[]> generator)

This method takes one argument. This method returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.

Parameters: One parameter is required for this method.

generator: a function that produces a new array of the desired type and the provided length.

Returns: an array containing all of the elements in this collection.

Throws:

1. ArrayStoreException - if the runtime type of any element in this collection is not assignable to the runtime component type of the generated array.

2. NullPointerException - if the generator function is null.

Approach 1: When no exception

Java

import java.util.Arrays;
import java.util.Vector;
import java.util.function.IntFunction;

public class VectortoArray2 {
    public static void main(String[] args) {

        Vector<String> vector = new Vector<>();

        vector.add("Hello");
        vector.add("Java");
        vector.add("C++");
        vector.add("Program");

        IntFunction<String[]> generator =
new IntFunction<String[]>() {

            @Override
            public String[] apply(int value) {
                String[] arr = { "Hello", "Java" };

                return arr;
            }
        };

        System.out.println(Arrays.toString(
vector.toArray(generator)));
    }
}

Output:

[Hello, Java, C++, Program]


Approach 2: NullPointerException

Java

import java.util.Arrays;
import java.util.Vector;
import java.util.function.IntFunction;

public class VectortoArray2 {
    public static void main(String[] args) {

        Vector<String> vector = new Vector<>();

        vector.add("Hello");
        vector.add("Java");
        vector.add("C++");
        vector.add("Program");

        IntFunction<String[]> generator = null;

        System.out.println(Arrays.toString(
vector.toArray(generator)));
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.function.IntFunction.apply(int)" because "generator" is null at java.base/java.util.Collection.toArray(Collection.java:413)


No comments:

Post a Comment