Arrays.parallelPrefix(int[], IntBinaryOperator) in Java

Arrays.parallelPrefix(int[], IntBinaryOperator): This method is available in java.util.Arrays class of Java.

Syntax:

void java.util.Arrays.parallelPrefix(int[] array, IntBinaryOperator op)

This method takes two arguments one of tye int array and the other of type IntBinaryOperator as its parameters. This method cumulates, in parallel, each element of the given array in place, using the supplied function.

Parameters: Two parameters are required for this method.

array: the array, which is modified in-place by this method.

op: a side-effect-free, associative function to perform the accumulation.

Throws:

NullPointerException - if the specified array or function is null.

Approach 1: When no exceptions

Java

import java.util.Arrays;
import java.util.function.IntBinaryOperator;

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

        int array[] = { 1, 2, 3, 4 };

        IntBinaryOperator sum = (d1, d2) -> d1 + d2;
        Arrays.parallelPrefix(array, sum);

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

Output:

[1, 3, 6, 10]


Approach 2: NullPointerException 

Java

import java.util.Arrays;
import java.util.function.IntBinaryOperator;

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

        int array[] = null;

        IntBinaryOperator sum = (d1, d2) -> d1 + d2;
        Arrays.parallelPrefix(array, sum);

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

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "array" is null at java.base/java.util.Arrays.parallelPrefix(Arrays.java:1526)



No comments:

Post a Comment