java.nio.ShortBuffer類的allocate()方法用於分配新的短緩衝區。
盡管標記未定義,但新緩衝區的位置將為零且其容量是其極限,並且每個元素都初始化為零。它將有一個支持數組,且數組偏移為零。
用法:
public static ShortBuffer allocate(int capacity)
參數:該方法接受強製性參數容量,以簡寫形式指定新緩衝區的容量。
返回值:此方法返回新的ShortBuffer。
異常:如果容量為負整數,則此方法引發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 ShortBuffer
int capacity = 5;
// Creating the ShortBuffer
// creating object of Shortbuffer
// and allocating size capacity
ShortBuffer sb = ShortBuffer.allocate(capacity);
// putting the value in Shortbuffer
sb.put((short)10000);
sb.put((short)10640);
sb.put((short)10189);
sb.put((short)-2000);
sb.put((short)-16780);
// Printing the ShortBuffer
System.out.println("ShortBuffer: "
+ Arrays.toString(sb.array()));
}
}
輸出:
ShortBuffer: [10000, 10640, 10189, -2000, -16780]
示例2:顯示NullPointerException
// 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 ShortBuffer
// by negetive integer
int capacity = -10;
// Creating the ShortBuffer
try {
// creating object of shortbuffer
// and allocating size with negative 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
參考: https://docs.oracle.com/javase/7/docs/api/java/nio/ShortBuffer.html#allocate()
相關用法
- Java ShortBuffer put(int, short)用法及代碼示例
- Java ShortBuffer limit()用法及代碼示例
- Java ShortBuffer compareTo用法及代碼示例
- Java ShortBuffer hashCode()用法及代碼示例
- Java ShortBuffer compact()用法及代碼示例
- Java ShortBuffer arrayOffset()用法及代碼示例
- Java ShortBuffer slice()用法及代碼示例
- Java ShortBuffer asReadOnlyBuffer()用法及代碼示例
- Java ShortBuffer order()用法及代碼示例
- Java ShortBuffer rewind()用法及代碼示例
- Java ShortBuffer mark()用法及代碼示例
- Java ShortBuffer hasArray()用法及代碼示例
- Java ShortBuffer duplicate()用法及代碼示例
- Java ShortBuffer reset()用法及代碼示例
- Java ShortBuffer isDirect()用法及代碼示例
注:本文由純淨天空篩選整理自IshwarGupta大神的英文原創作品 ShortBuffer allocate() method in Java With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。