get(int, byte[]): This method is available in java.nio.ByteBuffer class of Java.
Syntax:
ByteBuffer java.nio.ByteBuffer.get(int index, byte[] dst)
This method takes two arguments one of type int and another of type byte array as its parameters. This method transfers bytes from this buffer into the given destination array. The position of this buffer is unchanged.
Parameters: Two parameters are required for this method.
index: The index in this buffer from which the first byte will be read; must be non-negative and less than limit().
dst: The destination array.
Returns: This buffer.
Throws:
IndexOutOfBoundsException - If the index is negative, not smaller than limit(),or limit() - index < dst.length.
Approach 1: When no exceptions.
Java
import java.nio.ByteBuffer;public class ByteBufferget4 {public static void main(String[] args) {byte array[] = { 1, 2, 3, 4, 89, 2, 57, 13, 34 };ByteBuffer bb = ByteBuffer.wrap(array);int index = 0;byte dst[] = { 12, 34, 56, 78 };System.out.println(bb.get(index, dst));}}
Output:
java.nio.HeapByteBuffer[pos=0 lim=9 cap=9]
Approach 2: IndexOutOfBoundsException
Java
import java.nio.ByteBuffer;public class ByteBufferget4 {public static void main(String[] args) {byte array[] = { 1, 2, 3, 4, 89, 2, 57, 13, 34 };ByteBuffer bb = ByteBuffer.wrap(array);int index = -1;byte dst[] = { 12, 34, 56, 78 };System.out.println(bb.get(index, dst));}}
Output:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Range [-1, -1 + 4) out of bounds for length 9 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.HeapByteBuffer.get(HeapByteBuffer.java:193) at java.base/java.nio.ByteBuffer.get(ByteBuffer.java:898)
No comments:
Post a Comment