Java 中 DoubleBuffer 的 slice() 方法


在 java.nio.DoubleBuffer 類中可以使用方法 slice() 建立一個新 DoubleBuffer,其內容是原始 DoubleBuffer 的共享子序列。如果原始緩衝是隻讀的,則此方法返回新 DoubleBuffer,該 DoubleBuffer 是隻讀的;如果原始緩衝是直接的,則返回的 DoubleBuffer 是直接的。

演示這一點的程式如下 −

示例

 即時演示

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("
The 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 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

更新於: 2019 年 7 月 30 日

92 次瀏覽

啟動您的 職業生涯

完成課程獲取認證

開始
廣告