关于flip,看到JDK的文档大概是这么说的:“将limit属性设置为当前的位置”;而关于rewind方法,是在limit属性已经被设置合适的情况下使用的。也就是说这两个方法虽然都能够使指针返回到缓冲区的第一个位置,但是flip在调整指针之前,将limit属性设置为当前位置。
以下程序可以验证:
package com.bijian.study; import java.nio.*; public class IntBufferDemo { /** * @param args */ private static final int BSIZE = 1024; public static void main(String[] args) { ByteBuffer bb = ByteBuffer.allocate(BSIZE); IntBuffer ib = bb.asIntBuffer(); // view buffer // 存储int的数组 ib.put(new int[] { 11, 42, 47, 99, 143, 811, 1016 }); // 绝对位置读写 //System.out.println(ib.get(3)); System.out.println("*******************************"); System.out.println(ib.limit()); ib.put(3, 1811); ib.flip(); //ib.rewind(); System.out.println(ib.limit()); System.out.println("*******************************"); while (ib.hasRemaining()) { int i = ib.get(); System.out.println(i); } } }
运行结果:
******************************* 256 7 ******************************* 11 42 47 1811 143 811 1016
将flip()替换成rewind()如下:
package com.bijian.study; import java.nio.*; public class IntBufferDemo { /** * @param args */ private static final int BSIZE = 1024; public static void main(String[] args) { ByteBuffer bb = ByteBuffer.allocate(BSIZE); IntBuffer ib = bb.asIntBuffer(); // view buffer // 存储int的数组 ib.put(new int[] { 11, 42, 47, 99, 143, 811, 1016 }); // 绝对位置读写 //System.out.println(ib.get(3)); System.out.println("*******************************"); System.out.println(ib.limit()); ib.put(3, 1811); //ib.flip(); ib.rewind(); System.out.println(ib.limit()); System.out.println("*******************************"); while (ib.hasRemaining()) { int i = ib.get(); System.out.println(i); } } }
运行结果:
******************************* 256 256 ******************************* 11 42 47 1811 143 811 1016 0 0 0 0 0 ...
我们看到除了打印出数组中我们设置的内容之外,还会在后面打印出一系列自动设置的零值。