DoubleBuffer slice() method in Java



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
Updated on: 2019-07-30T22:30:25+05:30

141 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements