LongBuffer get(int, long[]) in Java

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

Syntax:

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

This method takes two arguments one of type int and another of type long array as its parameter. This method transfers longs from this buffer into the given destination array.

Parameters: One parameter is 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 the limit().

dst: The destination array.

Returns: This buffer.

Throws:

IndexOutOfBoundsException - If index is negative, not smaller than limit(),or limit() - index < dst.length

Approach 1: When no exceptions.

Java

import java.nio.LongBuffer;

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

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

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

Output:

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


Approach 2: IndexOutOfBoundsException 

Java

import java.nio.LongBuffer;

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

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

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


Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Range [-1, -1 + 3) 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) at java.base/java.nio.LongBuffer.get(LongBuffer.java:898)


No comments:

Post a Comment