LongBuffer put(int, long[]) in Java

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

Syntax:

LongBuffer java.nio.LongBuffer.put(int index, long[] src)

This method takes two arguments one of type int and another of type long array as its parameters. This method copies longs into this buffer from the given source array.

Note: The position of this buffer is unchanged.

Parameters: Two parameters are required for this method.

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

src: The array from which longs are to be read.

Returns: This buffer.

Throws:

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

2. ReadOnlyBufferException - If this buffer is read-only.

Approach 1: When no exceptions

Java

import java.nio.LongBuffer;

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

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

        int index = 0;
        long src[] = { 2, 3, 4 };
        System.out.println(lb.put(index, src));
    }
}

Output:

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


Approach 2: IndexOutOfBoundsException 

Java

import java.nio.LongBuffer;

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

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

        int index = 0;
        long src[] = { 2, 3, 4, 5, 6 };
        System.out.println(lb.put(index, src));
    }
}


Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Range [0, 0 + 5) 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.put(HeapLongBuffer.java:257) at java.base/java.nio.LongBuffer.put(LongBuffer.java:1189)



Approach 3: ReadOnlyBufferException 

Java

import java.nio.LongBuffer;

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

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

        int index = 0;
        long src[] = { 2, 3, 4 };

        LongBuffer readOnly = lb.asReadOnlyBuffer();
        System.out.println(readOnly.put(index, src));
    }
}


Output:

Exception in thread "main" java.nio.ReadOnlyBufferException at java.base/java.nio.HeapLongBufferR.put(HeapLongBufferR.java:262) at java.base/java.nio.LongBuffer.put(LongBuffer.java:1189)


Some more put Methods.


put(long)


put(long[])


put(LongBuffer)


put(int, long)


put(long[], int, int)


put(int, long[], int, int)



No comments:

Post a Comment