Java DoubleBuffer limit()方法及实例
java.nio.DoubleBuffer类的 limit() 方法是用来修改这个DoubleBuffer的极限。这个方法以要设置的极限为参数,并将其设置为这个Buffer的新极限。如果这个Buffer的标记已经被定义,并且大于新指定的极限,那么这个新的极限就不会被设置并被丢弃。
语法
public final DoubleBuffer limit(int newLimit)
返回值: 该方法在将指定的新极限作为该Buffer的新极限后返回该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 DoubleBuffer
// using allocate() method
DoubleBuffer doubleBuffer
= DoubleBuffer.allocate(4);
// put double value in doubleBuffer
// using put() method
doubleBuffer.put(20.5);
doubleBuffer.put(30.5);
// print the double buffer
System.out.println("DoubleBuffer before "
+ "setting buffer's limit: "
+ Arrays.toString(
doubleBuffer.array())
+ "\nPosition: "
+ doubleBuffer.position()
+ "\nLimit: "
+ doubleBuffer.limit());
// Limit the doubleBuffer
// using limit() method
doubleBuffer.limit(1);
// print the double buffer
System.out.println("\nDoubleBuffer after "
+ "setting buffer's limit: "
+ Arrays.toString(
doubleBuffer.array())
+ "\nPosition: "
+ doubleBuffer.position()
+ "\nLimit: "
+ doubleBuffer.limit());
}
}
输出:
DoubleBuffer before setting buffer's limit: [20.5, 30.5, 0.0, 0.0]
Position: 2
Limit: 4
DoubleBuffer 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 DoubleBuffer
// using allocate() method
DoubleBuffer doubleBuffer
= DoubleBuffer.allocate(5);
// put double value in DoubleBuffer
// using put() method
doubleBuffer.put(20.5);
doubleBuffer.put(30.5);
doubleBuffer.put(40.5);
// mark will be going to
// discarded by limit()
doubleBuffer.mark();
// print the double buffer
System.out.println("DoubleBuffer before "
+ "setting buffer's limit: "
+ Arrays.toString(
doubleBuffer.array())
+ "\nPosition: "
+ doubleBuffer.position()
+ "\nLimit: "
+ doubleBuffer.limit());
// Limit the doubleBuffer
// using limit() method
doubleBuffer.limit(4);
// print the double buffer
System.out.println("\nDoubleBuffer before "
+ "setting buffer's limit: "
+ Arrays.toString(
doubleBuffer.array())
+ "\nPosition: "
+ doubleBuffer.position()
+ "\nLimit: "
+ doubleBuffer.limit());
}
}
输出:
DoubleBuffer before setting buffer's limit: [20.5, 30.5, 40.5, 0.0, 0.0]
Position: 3
Limit: 5
DoubleBuffer 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/DoubleBuffer.html#limit-int-