A new ShortBuffer with the content as a shared subsequence of the original ShortBuffer can be created using the method slice() in the class java.nio.ShortBuffer. This method returns the new ShortBuffer 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 −
import java.nio.*; import java.util.*; public class Demo { public static void main(String[] args) { int n = 5; try { ShortBuffer buffer1 = ShortBuffer.allocate(n); buffer1.put((short)25); buffer1.put((short)18); buffer1.put((short)30); System.out.println("The Original ShortBuffer is: " + Arrays.toString(buffer1.array())); System.out.println("The position is: " + buffer1.position()); System.out.println("The capacity is: " + buffer1.capacity()); ShortBuffer buffer2 = buffer1.slice(); System.out.println("\nThe Subsequence ShortBuffer 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 −
The Original ShortBuffer is: [25, 18, 30, 0, 0] The position is: 3 The capacity is: 5 The Subsequence ShortBuffer is: [25, 18, 30, 0, 0] The position is: 0 The capacity is: 2