Java中的 LongBuffer allocate() 方法
Java.nio.LongBuffer 类的allocate()方法用于在现有缓冲区旁边分配一个新的Long缓冲区。新缓冲区的位置将为零。它的极限将是它的容量。它的标记将是未定义的。并且它的每个元素都将被初始化为零。它将有一个支持数组,并且它的数组偏移量为零。
句法:
public static LongBuffer allocate(Long capacity)
参数:此方法将新缓冲区的容量(Long)作为参数。
返回值:此方法返回新的 Long 缓冲区。
异常:如果容量为负 Longer,此方法将引发IllegalArgumentException 。
下面的程序说明了 allocate() 方法:
方案一:
Java
// Java program to demonstrate
// allocate() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Declaring the capacity of the LongBuffer
int Capacity = 10;
// Creating the LongBuffer
// creating object of Longbuffer
// and allocating size capacity
LongBuffer ib = LongBuffer.allocate(Capacity);
// putting the value in Longbuffer
ib.put(11);
ib.put(2, 19);
System.out.println("LongBuffer: "
+ Arrays.toString(ib.array()));
}
}
Java
// Java program to demonstrate
// allocate() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Declaring the capacity of the LongBuffer
// by negative Longer
int Capacity = -10;
// Creating the LongBuffer
try {
// creating object of Longbuffer
// and allocating size with negative Longer
System.out.println("Trying to allocate a Negative Longer");
LongBuffer ib = LongBuffer.allocate(Capacity);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown: " + e);
}
}
}
输出:
LongBuffer: [11, 0, 19, 0, 0, 0, 0, 0, 0, 0]
程序2:演示IllegalArgumentException
Java
// Java program to demonstrate
// allocate() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Declaring the capacity of the LongBuffer
// by negative Longer
int Capacity = -10;
// Creating the LongBuffer
try {
// creating object of Longbuffer
// and allocating size with negative Longer
System.out.println("Trying to allocate a Negative Longer");
LongBuffer ib = LongBuffer.allocate(Capacity);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown: " + e);
}
}
}
输出
Trying to allocate a Negative Longer
Exception thrown: java.lang.IllegalArgumentException: capacity < 0: (-10 < 0)