Java DoubleBuffer allocate()方法及实例

Java DoubleBuffer allocate()方法及实例

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

public static DoubleBuffer 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 DoubleBuffer
        int capacity = 10;
 
        // Creating the DoubleBuffer
 
        // creating object of Doublebuffer
        // and allocating size capacity
        DoubleBuffer db = DoubleBuffer.allocate(capacity);
 
        // putting the value in Doublebuffer
        db.put(8.56F);
        db.put(2, 9.61F);
 
        System.out.println("DoubleBuffer: "
                           + Arrays.toString(db.array()));
    }
}

输出

DoubleBuffer: [8.5600004196167, 0.0, 9.609999656677246, 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 DoubleBuffer
        // by negative integer
        int capacity = -10;
 
        // Creating the DoubleBuffer
        try {
 
            // creating object of Doublebuffer
            // and allocating size with negative integer
            System.out.println("Trying to allocate a negative integer");
 
            DoubleBuffer db = DoubleBuffer.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教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程