LongBuffer get(int, long[], int, int) in Java

get(int, long[], int, int): This method is available in java.nio.LongBuffer class of Java.

Syntax:

LongBuffer java.nio.LongBuffer.get(int index, long[] dst, int offset, int length)

This method takes four arguments, three of them are of types int and one of type long array as its parameters. This method transfers length longs from this buffer into the given array, starting at the given index in this buffer and at the given offset in the array.

Parameters: Four parameters are required for this method.

index: The index in this buffer from which the first long will be read; must be non-negative and less than limit().

dst: The destination array.

offset: The offset within the array of the first long to be written; must be non-negative and less than dst.length.

length: The number of longs to be written to the given array; must be non-negative and no larger than the smaller of limit() - index and dst.length - offset.

Returns: This buffer.

Throws:

IndexOutOfBoundsException - If the preconditions on the index, offset, and length parameters do not hold.

Approach 1: When no exceptions.

Java

import java.nio.LongBuffer;

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

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

        long dst[] = { 1, 2, 3, 4 };
        int offset = 0;
        int length = 2;
        int index = 2;
        System.out.println(lb.get(index, dst, offset, length));
    }
}

Output:

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


Approach 2: IndexOutOfBoundsException 

Java

import java.nio.LongBuffer;

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

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

        long dst[] = { 1, 2, 3, 4 };
        int offset = 0;
        int length = 2;
        int index = -1;
        System.out.println(lb.get(index, dst, offset, length));
    }
}


Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Range [-1, -1 + 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.get(HeapLongBuffer.java:193)


No comments:

Post a Comment