📌  相关文章
📜  Java中的 FloatBuffer allocate() 方法及示例

📅  最后修改于: 2022-05-13 01:55:12.938000             🧑  作者: Mango

Java中的 FloatBuffer allocate() 方法及示例

Java.nio.FloatBuffer 类allocate()方法用于在现有缓冲区旁边分配一个新的浮点缓冲区。新缓冲区的位置将为零。它的极限将是它的容量。它的标记将是未定义的。并且它的每个元素都将被初始化为零。它将有一个支持数组,并且它的数组偏移量为零。
句法:

public static FloatBuffer allocate(int capacity)

参数:此方法将新缓冲区的容量(以浮点数形式)作为参数。
返回值:此方法返回新的浮点缓冲区
异常:如果容量为负整数,此方法将引发IllegalArgumentException
下面的程序说明了 allocate() 方法:
示例 1:

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 FloatBuffer
        int capacity = 10;
 
        // Creating the FloatBuffer
 
        // creating object of floatbuffer
        // and allocating size capacity
        FloatBuffer fb = FloatBuffer.allocate(capacity);
 
        // putting the value in floatbuffer
        fb.put(8.56F);
        fb.put(2, 9.61F);
 
        System.out.println("FloatBuffer: "
                           + Arrays.toString(fb.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 FloatBuffer
        // by negative integer
        int capacity = -10;
 
        // Creating the FloatBuffer
        try {
 
            // creating object of floatbuffer
            // and allocating size with negative integer
            System.out.println("Trying to allocate a negative integer");
 
            FloatBuffer fb = FloatBuffer.allocate(capacity);
        }
        catch (IllegalArgumentException e) {
            System.out.println("Exception thrown: " + e);
        }
    }
}


输出:
FloatBuffer: [8.56, 0.0, 9.61, 0.0, 0.0, 0.0, 0.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 FloatBuffer
        // by negative integer
        int capacity = -10;
 
        // Creating the FloatBuffer
        try {
 
            // creating object of floatbuffer
            // and allocating size with negative integer
            System.out.println("Trying to allocate a negative integer");
 
            FloatBuffer fb = FloatBuffer.allocate(capacity);
        }
        catch (IllegalArgumentException e) {
            System.out.println("Exception thrown: " + e);
        }
    }
}
输出
Trying to allocate a negative integer
Exception thrown: java.lang.IllegalArgumentException: capacity < 0: (-10 < 0)