LongBuffer slice(int, int) in Java

slice(int, int): This method is available in java.nio.LongBuffer class of Java.

Syntax:

LongBuffer java.nio.LongBuffer.slice(int index, int length)

This method takes two arguments of type int as its parameters. This method creates a new long buffer whose content is a shared subsequence of this buffer's content.

Note: The content of the new buffer will start at position index in this buffer, and will contain length elements.

Parameters: Two parameters are required for this method.

index: The position in this buffer at which the content of the new buffer will start; must be non-negative and no larger than limit().

length: The number of elements the new buffer will contain; must be non-negative and no larger than limit() - index.

Returns: The new buffer.

Throws:

1. IndexOutOfBoundsException - If index is negative or greater than limit(), length is negative, or length > limit() - index.

Approach 1: When no exceptions

Java

import java.nio.LongBuffer;

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

        long array[] = { 1, 2, 3, 4 };
        LongBuffer lb = LongBuffer.wrap(array);

        int index = 0, length = 2;
        System.out.println(lb.slice(index, length));
    }
}

Output:

java.nio.HeapLongBuffer[pos=0 lim=2 cap=2]


Approach 2: IndexOutOfBoundsException 

Java

import java.nio.LongBuffer;

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

        long array[] = { 1, 2, 3, 4 };
        LongBuffer lb = LongBuffer.wrap(array);

        int index = 3, length = 2;
        System.out.println(lb.slice(index, length));
    }
}


Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Range [3, 3 + 2) out of bounds for length 4 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckFromIndexSize(Preconditions.java:82) at java.base/jdk.internal.util.Preconditions.checkFromIndexSize(Preconditions.java:343) at java.base/java.util.Objects.checkFromIndexSize(Objects.java:411) at java.base/java.nio.HeapLongBuffer.slice(HeapLongBuffer.java:121)


slice()

No comments:

Post a Comment