Java FloatBuffer allocate()方法在Java中的应用实例

Java FloatBuffer allocate()方法在Java中的应用实例

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

public static FloatBuffer allocate(int capacity)

参数: 该方法接受新的缓冲区的 容量 ,单位是浮点,作为参数。

返回值 :该方法返回 新的浮点缓冲区。

异常: 如果容量是一个负的整数,该方法会抛出 IllegalArgumentException

以下程序说明了allocate()方法:

示例1:

// 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()));
    }
}

输出

FloatBuffer: [8.56, 0.0, 9.61, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

实例2: 为了证明IllegalArgumentException

// 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)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程