Arrays.setAll(long[], IntToLongFunction) in Java

Arrays.setAll(long[], IntToLongFunction): This method is available in java.util.Arrays class of Java.

Syntax:

void java.util.Arrays.setAll(long[] array, IntToLongFunction generator)

This method takes two arguments one of type long array and the other of type IntToLongFunction as its parameters. This method sets all elements of the specified array, using the provided generator function to compute each element.

Parameters: Two parameters are required for this method.

array: array to be initialized.

generator: a function accepting an index and producing the desired value for that position.

Throws:

NullPointerException - if the generator is null.

Approach 1: When no exceptions

Java

import java.util.Arrays;
import java.util.function.IntToLongFunction;

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

        long array[] = { 1, 2, 4, 5, 6 };

        IntToLongFunction generator = intVal -> {
            long longVal = intVal;
            return longVal;
        };

        Arrays.setAll(array, generator);

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

    }
}

Output:

[0, 1, 2, 3, 4]


Approach 2: NullPointerException 

Java

import java.util.Arrays;
import java.util.function.IntToLongFunction;

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

        long array[] = { 1, 2, 4, 5, 6 };

        IntToLongFunction generator = null;
        Arrays.setAll(array, generator);

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

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.Arrays.setAll(Arrays.java:5170)


No comments:

Post a Comment