DoubleBuffer slice() method in Java

Java 8Object Oriented ProgrammingProgramming

A new DoubleBuffer with the content as a shared subsequence of the original DoubleBuffer can be created using the method slice() in the class java.nio.DoubleBuffer. This method returns the new DoubleBuffer 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 {
         DoubleBuffer buffer1 = DoubleBuffer.allocate(n);
         buffer1.put(4.5D);
         buffer1.put(1.2D);
         buffer1.put(3.9D);
         System.out.println("The Original DoubleBuffer is: " + Arrays.toString(buffer1.array()));
         System.out.println("The position is: " + buffer1.position());
         System.out.println("The capacity is: " + buffer1.capacity());
         DoubleBuffer buffer2 = buffer1.slice();
         System.out.println("\nThe Subsequence DoubleBuffer is: " + Arrays.toString(buffer2.array()));
         System.out.println("The position is: " + buffer2.position());
         System.out.println("The capacity is: " + buffer2.capacity());
      } 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 DoubleBuffer is: [4.5, 1.2, 3.9, 0.0, 0.0]
The position is: 3
The capacity is: 5

The Subsequence DoubleBuffer is: [4.5, 1.2, 3.9, 0.0, 0.0]
The position is: 0
The capacity is: 2
raja
Published on 01-Mar-2019 11:16:20
Advertisements