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 次瀏覽

開啟職業生涯

完成課程並獲得認證

開始
廣告