Java 中的 IntBuffer wrap() 方法
可以使用 java.nio.IntBuffer 類中的 wrap() 方法將 int 陣列封裝到緩衝區中。此方法需要一個引數,即要封裝到緩衝區的陣列,它會返回建立的新緩衝區。如果修改了返回的緩衝區,則陣列的內容也會以類似的方式修改,反之亦然。
以下提供了一個演示此操作的程式 −
示例
import java.nio.*; import java.util.*; public class Demo { public static void main(String[] args) { try { int[] arr = { 8, 1, 3, 7, 5 }; System.out.println("The array length is: " + arr.length); System.out.println("Array elements are: " + Arrays.toString(arr)); IntBuffer buffer = IntBuffer.wrap(arr); buffer.rewind(); System.out.println("
The IntBuffer is: " + Arrays.toString(buffer.array())); System.out.println("The position is: " + buffer.position()); System.out.println("The capacity is: " + buffer.capacity()); } catch (IllegalArgumentException e) { System.out.println("Error!!! IllegalArgumentException"); } catch (ReadOnlyBufferException e) { System.out.println("Error!!! ReadOnlyBufferException"); } } }
上述程式的輸出如下 −
輸出
The array length is: 5 Array elements are: [8, 1, 3, 7, 5] The IntBuffer is: [8, 1, 3, 7, 5] The position is: 0 The capacity is: 5
廣告