Arrays.spliterator(long[], int, int) in Java

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

Syntax:

OfLong java.util.Arrays.spliterator(long[] array, int startInclusive, int endExclusive)

This method takes three arguments one of type long array and the rest two are of type int as its parameters. This method returns a Spliterator.OfLong covering the specified range of the specified array.

Parameters: Three parameters are required for this method.

array: the array, assumed to be unmodified during use.

startInclusive: the first index to cover, inclusive.

endExclusive: index immediately past the last index to cover.

Returns: a spliterator for the array elements.

Throws:

1. ArrayIndexOutOfBoundsException - if startInclusive is negative, endExclusive is less than startInclusive, or endExclusive is greater than the array size.

Approach 1: When no exceptions

Java

import java.util.Arrays;

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

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

        int startInclusive = 0, endExclusive = 2;

        System.out.println(Arrays.spliterator(array,
startInclusive, endExclusive));
    }
}

Output:

java.util.Spliterators$LongArraySpliterator@39ed3c8d


Approach 2: ArrayIndexOutOfBoundsException 

Java

import java.util.Arrays;

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

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

        int startInclusive = 3, endExclusive = 2;

        System.out.println(Arrays.spliterator(array,
startInclusive, endExclusive));
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: origin(3) > fence(2) at java.base/java.util.Spliterators.checkFromToBounds(Spliterators.java:387) at java.base/java.util.Spliterators.spliterator(Spliterators.java:305) at java.base/java.util.Arrays.spliterator(Arrays.java:5373) at com.example.Arrays.Arraysspliteratorlongrange.main(Arraysspliteratorlongrange.java:12)


No comments:

Post a Comment