java.nio.FloatBuffer類的allocate()方法用於在現有緩衝區旁邊分配一個新的float緩衝區。新緩衝區的位置將為零。它的極限將是它的容量。其標記將是不確定的。並且其每個元素都將初始化為零。它將有一個支持數組,其數組偏移量將為零。
用法:
public static FloatBuffer allocate(int capacity)
參數:此方法將新緩衝區的容量(以float表示)作為參數。
返回值:此方法返回新的float緩衝區。
異常:如果容量為負整數,則此方法引發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 negetive integer
int capacity = -10;
// Creating the FloatBuffer
try {
// creating object of floatbuffer
// and allocating size with negetive integer
System.out.println("Trying to allocate a negetive integer");
FloatBuffer fb = FloatBuffer.allocate(capacity);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown: " + e);
}
}
}
輸出:
Trying to allocate a negetive integer Exception thrown: java.lang.IllegalArgumentException
相關用法
- Java FloatBuffer compareTo()用法及代碼示例
- Java FloatBuffer slice()用法及代碼示例
- Java FloatBuffer wrap()用法及代碼示例
- Java FloatBuffer hasArray()用法及代碼示例
- Java FloatBuffer equals()用法及代碼示例
- Java FloatBuffer array()用法及代碼示例
- Java FloatBuffer asReadOnlyBuffer()用法及代碼示例
- Java FloatBuffer limit()用法及代碼示例
- Java FloatBuffer duplicate()用法及代碼示例
- Java FloatBuffer compact()用法及代碼示例
- Java FloatBuffer arrayOffset()用法及代碼示例
- Java CharBuffer allocate()用法及代碼示例
- Java ShortBuffer allocate()用法及代碼示例
- Java DoubleBuffer allocate()用法及代碼示例
- Java ByteBuffer allocate()用法及代碼示例
注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 FloatBuffer allocate() method in Java With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。