Java中的 ShortBuffer limit() 方法及示例
Java.nio.ShortBuffer 类的limit()方法用来修改这个ShortBuffer 的限制。此方法将要设置的限制作为参数,并将其设置为此 Buffer 的新限制。如果这个 Buffer 的标记已经定义并且大于新的指定限制,那么这个新的限制不会被设置并被丢弃。
句法:
public final ShortBuffer limit(int newLimit)
参数:此方法接受一个参数newLimit ,它是限制的新整数值。
返回值:该方法将指定的新限制设置为该Buffer的新限制后返回该缓冲区。
以下是说明 limit() 方法的示例:
示例 1:
// Java program to demonstrate
// limit() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// defining and allocating ShortBuffer
// using allocate() method
ShortBuffer shortBuffer
= ShortBuffer.allocate(4);
// put short value in ShortBuffer
// using put() method
shortBuffer.put((short)20);
shortBuffer.put((short)30);
// print the short buffer
System.out.println(
"ShortBuffer before "
+ "setting buffer's limit: "
+ Arrays.toString(
shortBuffer.array())
+ "\nPosition: "
+ shortBuffer.position()
+ "\nLimit: "
+ shortBuffer.limit());
// Limit the shortBuffer
// using limit() method
shortBuffer.limit(1);
// print the short buffer
System.out.println(
"\nShortBuffer after "
+ "setting buffer's limit: "
+ Arrays.toString(
shortBuffer.array())
+ "\nPosition: "
+ shortBuffer.position()
+ "\nLimit: "
+ shortBuffer.limit());
}
}
输出:
ShortBuffer before setting buffer's limit: [20, 30, 0, 0]
Position: 2
Limit: 4
ShortBuffer after setting buffer's limit: [20, 30, 0, 0]
Position: 1
Limit: 1
示例 2:
// Java program to demonstrate
// limit() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// defining and allocating ShortBuffer
// using allocate() method
ShortBuffer shortBuffer
= ShortBuffer.allocate(5);
// put short value in ShortBuffer
// using put() method
shortBuffer.put((short)20);
shortBuffer.put((short)30);
shortBuffer.put((short)40);
// mark will be going to
// discarded by limit()
shortBuffer.mark();
// print the short buffer
System.out.println(
"ShortBuffer before "
+ "setting buffer's limit: "
+ Arrays.toString(
shortBuffer.array())
+ "\nPosition: "
+ shortBuffer.position()
+ "\nLimit: "
+ shortBuffer.limit());
// Limit the shortBuffer
// using limit() method
shortBuffer.limit(4);
// print the short buffer
System.out.println(
"\nShortBuffer before "
+ "setting buffer's limit: "
+ Arrays.toString(
shortBuffer.array())
+ "\nPosition: "
+ shortBuffer.position()
+ "\nLimit: "
+ shortBuffer.limit());
}
}
输出:
ShortBuffer before setting buffer's limit: [20, 30, 40, 0, 0]
Position: 3
Limit: 5
ShortBuffer before setting buffer's limit: [20, 30, 40, 0, 0]
Position: 3
Limit: 4
参考: https://docs.oracle.com/javase/9/docs/api/ Java/nio/ShortBuffer.html#mark–