java.nio.CharBuffer 类的 slice() 方法
可以通过使用 java.nio.CharBuffer 类中的 slice() 方法,创建带有内容作为原始 CharBuffer 的共享子序列的新 CharBuffer。如果原始缓冲区是只读的,则此方法会返回新的 CharBuffer(该 CharBuffer 也是只读的);如果原始缓冲区是直接的,则返回新的 CharBuffer(该 CharBuffer 也是直接的)。
下面给出了演示该方法的一个程序 -
示例
import java.nio.*; import java.util.*; public class Demo { public static void main(String[] args) { int n = 5; try { CharBuffer buffer1 = CharBuffer.allocate(n); buffer1.put('A'); buffer1.put('B'); buffer1.put('C'); System.out.println("The Original CharBuffer is: " + Arrays.toString(buffer1.array())); System.out.println("The position is: " + buffer1.position()); System.out.println("The limit is: " + buffer1.limit()); CharBuffer buffer2 = buffer1.slice(); System.out.println("
The Subsequence CharBuffer 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 Original CharBuffer is: [A, B, C, , ] The position is: 3 The limit is: 5 The Subsequence CharBuffer is: [A, B, C, , ] The position is: 0 The limit is: 2
广告