Java中的IntBuffer wrap()方法

使用wrap()类java.nio.IntBuffer中的方法,可以将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("\nThe 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