IntBuffer compact() 方法在 Java 中


可以使用 java.nio.IntBuffer 類中的 compact() 方法壓縮緩衝區。此方法不需要引數,並且它會返回具有與原始緩衝區相同內容的新壓縮 IntBuffer。如果緩衝區是隻讀的,則會丟擲 ReadOnlyBufferException。

演示這一點的程式如下 −

示例

 線上演示

import java.nio.*;
import java.util.*;
public class Demo {
   public static void main(String[] args) {
      int n = 5;
      try {
         IntBuffer buffer = IntBuffer.allocate(n);
         buffer.put(3);
         buffer.put(7);
         buffer.put(5);
         System.out.println("The Original IntBuffer is: " + Arrays.toString(buffer.array()));
         System.out.println("The position is: " + buffer.position());
         System.out.println("The limit is: " + buffer.limit());
         IntBuffer bufferCompact = buffer.compact();
         System.out.println("
The Compacted IntBuffer is: " + Arrays.toString(bufferCompact.array()));          System.out.println("The position is: " + bufferCompact.position());          System.out.println("The limit is: " + bufferCompact.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 Compacted IntBuffer is: [0, 0, 5, 0, 0]
The position is: 2
The limit is: 5

更新於: 30-Jul-2019

110 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.