大家可以从下面这个例子看到,虽然 CharBuffer 实际操作的还是 ByteBuffer 但是为什么我向 CharBuffer 中写入2个字节,而在 ByteBuffer 中不可见呢?JDK上不是说 像asCharBuffer()等方法,此缓冲区内容的更改在新缓冲区中是可见的,反之亦然嘛,为什么呢?该怎么理解 asCharBuffer() 之类的方法呢?
public class formatTest{
public static void main(String[] args)throws IOException{
ByteBuffer bb = ByteBuffer.allocateDirect(10);
byte[] b1 = new byte[]{'a', 'b'};
bb.put(b1);
System.out.println(bb.position()); // 这里是 2
char[] c1 = new char[]{'c', 'd'};
CharBuffer cb = bb.asCharBuffer().put(c1);
System.out.println(bb.position()); // 这里是 2
bb.flip();
// cb.rewind();
while(bb.hasRemaining()){
System.out.println(bb.get());
}
}
}
public class formatTest{
public static void main(String[] args)throws IOException{
ByteBuffer bb = ByteBuffer.allocateDirect(10);
byte[] b1 = new byte[]{'a', 'b'};
bb.put(b1);
System.out.println(bb.position()); // 这里是 2
char[] c1 = new char[]{'c', 'd'};
CharBuffer cb = bb.asCharBuffer().put(c1);
System.out.println(bb.position()); // 这里是 2
bb.flip();
// cb.rewind();
while(bb.hasRemaining()){
System.out.println(bb.get());
}
}
}
但你仔细看一下:
The content of the new buffer will start at this buffer's current position. Changes to this buffer's content will be visible in the new buffer, and vice versa; the two buffers' position, limit, and values will be independent.这两个缓冲区的位置,界限和标记值是相互独立的。前面那句,说
Changes to this buffer's content will be visible in the new buffer, and vice versa;
我觉得是这个意思。
比如,你已经执行了
ByteBuffer bb = ByteBuffer.allocateDirect(10);
byte[] b1 = new byte[]{'a', 'b'};
bb.put(b1);
然后执行CharBuffer cb = bb.asCharBuffer().put(c1);
如果执行cb.rewind();,
在程序输出中,会打印出 99 和 100.
但你如果在cb.rewind();之前再执行几次bb.put(b1);试试呢。
就会把 99 和 100 冲掉。