IntBuffer get(int[], int, int) in Java

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

Syntax:

IntBuffer java.nio.IntBuffer.get(int[] dst, int offset, int length)

This method takes three arguments one of type int array and the other two are of type int as its parameter. This method transfers ints from this buffer into the given destination array.

Parameters: Three parameters are required for this method.

dst: The array into which ints are to be written.

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

length: The maximum number of ints to be written to the given array; must be non-negative and no larger than dst.length - offset.

Returns: This buffer.

Throws:

1. BufferUnderflowException - If there are fewer than length ints remaining in this buffer.

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

Approach 1: When no exceptions

Java

import java.nio.IntBuffer;

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

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

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

Output:

java.nio.HeapIntBuffer[pos=4 lim=4 cap=4]


Approach 2: BufferUnderflowException 

Java

import java.nio.IntBuffer;

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

        int array[] = { 1, 2, 3 };
        IntBuffer lb = IntBuffer.wrap(array);

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

Output:

Exception in thread "main" java.nio.BufferUnderflowException at java.base/java.nio.HeapIntBuffer.get(HeapIntBuffer.java:185)


Approach 3: IndexOutOfBoundsException

Java

import java.nio.IntBuffer;

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

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

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

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Range [0, 0 + 4) out of bounds for length 3 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.HeapIntBuffer.get(HeapIntBuffer.java:182)


Some more get methods.


get()


get(int)


get(int[])


get(int, int[])


get(int, int[], int, int)


No comments:

Post a Comment