Java IntBuffer flip()方法及实例

Java IntBuffer flip()方法及实例

java.nio.IntBuffer类flip() 方法是用来翻转这个缓冲区的。通过翻转这个缓冲区,意味着缓冲区将被修剪到当前位置,然后位置将被改变为零。在这个过程中,如果缓冲区上有任何标记,那么这个标记将被自动丢弃。

语法

public final IntBuffer flip()

参数: 该方法不接受任何参数。

返回值: 该方法返回翻转的IntBuffer实例。

下面是说明flip()方法的例子。

例子 1 :

// Java program to demonstrate
// flip() method
 
import java.nio.*;
import java.util.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // Declare and initialize
        // the int array
        int[] ib
            = { 10, 20, 30 };
 
        // wrap the int array
        // into IntBuffer
        // using wrap() method
        IntBuffer intBuffer
            = IntBuffer.wrap(ib);
 
        // set position at index 1
        intBuffer.position(1);
 
        // print the buffer
        System.out.println(
            "Buffer before flip: "
            + Arrays.toString(
                  intBuffer.array())
            + "\nPosition: "
            + intBuffer.position()
            + "\nLimit: "
            + intBuffer.limit());
 
        // Flip the Buffer
        // using flip() method
        intBuffer.flip();
 
        // print the buffer
        System.out.println(
            "\nBuffer after flip: "
            + Arrays.toString(
                  intBuffer.array())
            + "\nPosition: "
            + intBuffer.position()
            + "\nLimit: "
            + intBuffer.limit());
    }
}

输出

Buffer before flip: [10, 20, 30]
Position: 1
Limit: 3

Buffer after flip: [10, 20, 30]
Position: 0
Limit: 1

例子 2 :

// Java program to demonstrate
// flip() method
 
import java.nio.*;
import java.util.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // defining and allocating IntBuffer
        // using allocate() method
        IntBuffer intBuffer
            = IntBuffer.allocate(4);
 
        // put int value in IntBuffer
        // using put() method
        intBuffer.put(20);
        intBuffer.put(34);
 
        // set position at index 1
        intBuffer.position(1);
 
        // print the buffer
        System.out.println(
            "Buffer before flip: "
            + Arrays.toString(
                  intBuffer.array())
            + "\nPosition: "
            + intBuffer.position()
            + "\nLimit: "
            + intBuffer.limit());
 
        // Flip the Buffer
        // using flip() method
        intBuffer.flip();
 
        // print the buffer
        System.out.println(
            "\nBuffer after flip: "
            + Arrays.toString(
                  intBuffer.array())
            + "\nPosition: "
            + intBuffer.position()
            + "\nLimit: "
            + intBuffer.limit());
    }
}

输出

Buffer before flip: [20, 34, 0, 0]
Position: 1
Limit: 4

Buffer after flip: [20, 34, 0, 0]
Position: 0
Limit: 1

参考资料: https://docs.oracle.com/javase/9/docs/api/java/nio/IntBuffer.html#flip-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程