Arrays.parallelPrefix(double[], DoubleBinaryOperator) in Java

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

Syntax:

void java.util.Arrays.parallelPrefix(double[] array, DoubleBinaryOperator op)

This method takes two arguments one of type double array and the other of type DoubleBinaryOperator 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: side-effect-free function to perform the accumulation.

Returns: NA

Throws:

NullPointerException - if the specified array or function is null.

Approach 1: When no exceptions

Java

import java.util.Arrays;
import java.util.function.DoubleBinaryOperator;

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

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

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

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

Output:

[1.0, 3.0, 6.0, 10.0]


Approach 2: NullPointerException

Java

import java.util.Arrays;
import java.util.function.DoubleBinaryOperator;

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

        double array[] = null;

        DoubleBinaryOperator 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:1481)



No comments:

Post a Comment