IntBuffer slice() method in Java


A new IntBuffer with the content as a shared subsequence of the original IntBuffer can be created using the method slice() in the class java.nio.IntBuffer. This method returns the new IntBuffer that is read-only if the original buffer is read-only and direct if the original buffer is direct.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.nio.*;
import java.util.*;
public class Demo {
   public static void main(String[] args) {
      int n = 5;
      try {
         IntBuffer buffer1 = IntBuffer.allocate(n);
         buffer1.put(3);
         buffer1.put(7);
         buffer1.put(5);
         System.out.println("The Original IntBuffer is: " + Arrays.toString(buffer1.array()));
         System.out.println("The position is: " + buffer1.position());
         System.out.println("The limit is: " + buffer1.limit());
         IntBuffer buffer2 = buffer1.slice();
         System.out.println("
The Subsequence IntBuffer is: " + Arrays.toString(buffer2.array()));          System.out.println("The position is: " + buffer2.position());          System.out.println("The limit is: " + buffer2.limit());       } catch (IllegalArgumentException e) {          System.out.println("Error!!! IllegalArgumentException");       } catch (ReadOnlyBufferException e) {          System.out.println("Error!!! ReadOnlyBufferException");       }    } }

The output of the above program is as follows −

Output

The Original IntBuffer is: [3, 7, 5, 0, 0]
The position is: 3
The limit is: 5

The Subsequence IntBuffer is: [3, 7, 5, 0, 0]
The position is: 0
The limit is: 2

Updated on: 30-Jul-2019

88 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements