Java中的 FloatBuffer limit() 方法及示例
Java.nio.FloatBuffer 类的limit()方法用来修改这个FloatBuffer 的限制。此方法将要设置的限制作为参数,并将其设置为此 Buffer 的新限制。如果这个 Buffer 的标记已经定义并且大于新的指定限制,那么这个新的限制不会被设置并被丢弃。
句法:
public final FloatBuffer 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 FloatBuffer
// using allocate() method
FloatBuffer floatBuffer
= FloatBuffer.allocate(4);
// put float value in FloatBuffer
// using put() method
floatBuffer.put(20.5f);
floatBuffer.put(30.5f);
// print the float buffer
System.out.println(
"FloatBuffer before "
+ "setting buffer's limit: "
+ Arrays.toString(
floatBuffer.array())
+ "\nPosition: "
+ floatBuffer.position()
+ "\nLimit: "
+ floatBuffer.limit());
// Limit the floatBuffer
// using limit() method
floatBuffer.limit(1);
// print the float buffer
System.out.println(
"\nFloatBuffer after "
+ "setting buffer's limit: "
+ Arrays.toString(
floatBuffer.array())
+ "\nPosition: "
+ floatBuffer.position()
+ "\nLimit: "
+ floatBuffer.limit());
}
}
FloatBuffer before setting buffer’s limit:
[20.5, 30.5, 0.0, 0.0]
Position: 2
Limit: 4
FloatBuffer after setting buffer’s limit:
[20.5, 30.5, 0.0, 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 FloatBuffer
// using allocate() method
FloatBuffer floatBuffer
= FloatBuffer.allocate(5);
// put float value in FloatBuffer
// using put() method
floatBuffer.put(20.5f);
floatBuffer.put(30.5f);
floatBuffer.put(40.5f);
// mark will be going to
// discarded by limit()
floatBuffer.mark();
// print the float buffer
System.out.println(
"FloatBuffer before "
+ "setting buffer's limit: "
+ Arrays.toString(
floatBuffer.array())
+ "\nPosition: "
+ floatBuffer.position()
+ "\nLimit: "
+ floatBuffer.limit());
// Limit the floatBuffer
// using limit() method
floatBuffer.limit(4);
// print the double buffer
System.out.println(
"\nFloatBuffer before "
+ "setting buffer's limit: "
+ Arrays.toString(
floatBuffer.array())
+ "\nPosition: "
+ floatBuffer.position()
+ "\nLimit: "
+ floatBuffer.limit());
}
}
FloatBuffer before setting buffer’s limit:
[20.5, 30.5, 40.5, 0.0, 0.0]
Position: 3
Limit: 5
FloatBuffer before setting buffer’s limit:
[20.5, 30.5, 40.5, 0.0, 0.0]
Position: 3
Limit: 4
参考: https://docs.oracle.com/javase/9/docs/api/ Java/nio/FloatBuffer.html#limit-int-