IntBuffer 中的 slice() 方法


可以通过 java.nio.IntBuffer 类中的 slice() 方法创建新的 IntBuffer,其内容作为原始 IntBuffer 的共享子序列。如果原始缓冲区是只读的,这个方法将返回新的只读 IntBuffer;如果原始缓冲区是直接的,它将返回直接 IntBuffer。

演示此方法的程序如下 −

示例

 在线演示

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 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

更新日期:2019 年 7 月 30 日

114 次浏览

开启职业生涯

完成课程并获得认证

开始
广告
© . All rights reserved.