Java:CharBuffer";“忽略”;阵列偏移?

Java:CharBuffer";“忽略”;阵列偏移?,java,arrays,buffer,nio,Java,Arrays,Buffer,Nio,请帮助我理解以下内容: 我使用 CharBuffer.wrapped(新字符[12],2,10)(数组,偏移量,长度) 因此,我希望访问数组时偏移量为2,总(剩余)长度为10。但是arrayOffset()返回0 我想了解(但无法从JavaDoc中理解)的是: 当arrayOffset()不是0时 是否有可能让CharBuffer使用具有“实”偏移量的数组(以便在该偏移量之前永远不会访问该数组) 下面是一个小测试用例: import java.nio.*; import java.util.

请帮助我理解以下内容:

我使用
CharBuffer.wrapped(新字符[12],2,10)
(数组,偏移量,长度)
因此,我希望访问数组时偏移量为
2
,总(剩余)长度为
10
。但是
arrayOffset()
返回
0

我想了解(但无法从JavaDoc中理解)的是:

  • arrayOffset()
    不是
    0

  • 是否有可能让
    CharBuffer
    使用具有“实”偏移量的数组(以便在该偏移量之前永远不会访问该数组)

下面是一个小测试用例:

import java.nio.*;
import java.util.*;
import org.junit.*;

public class _CharBufferTests {

  public _CharBufferTests() {
  }

  private static void printBufferInfo(CharBuffer b) {
    System.out.println("- - - - - - - - - - - - - - -");
    System.out.println("capacity: " + b.capacity());
    System.out.println("length: " + b.length());
    System.out.println("arrayOffset: " + b.arrayOffset());
    System.out.println("limit: " + b.limit());
    System.out.println("position: " + b.position());
    System.out.println("remaining: " + b.remaining());
    System.out.print("content from array: ");

    char[] array = b.array();
    for (int i = 0; i < array.length; ++i) {
        if (array[i] == 0) {
            array[i] = '_';
        }
    }

    System.out.println(Arrays.toString(b.array()));
  }

  @Test
  public void testCharBuffer3() {
    CharBuffer b = CharBuffer.wrap(new char[12], 2, 10);
    printBufferInfo(b);
    b.put("abc");
    printBufferInfo(b);
    b.rewind();
    b.put("abcd");
    printBufferInfo(b);
  }

}
谢谢大家!

其支持数组将是给定数组,其数组偏移量将为零。


检查对
CharBuffer.offset的写入。看起来HeapCharBuffer和StringCharBuffer都可以具有非零ArrayOffset()。

我认为,您可以使用
位置来获得类似的结果。不要使用
倒带
,因为这会将
位置设置为0;改用
reset

- - - - - - - - - - - - - - -
capacity: 12
length: 10
arrayOffset: 0
limit: 12
position: 2
remaining: 10
content from array: [_, _, _, _, _, _, _, _, _, _, _, _]
- - - - - - - - - - - - - - -
capacity: 12
length: 7
arrayOffset: 0
limit: 12
position: 5
remaining: 7
content from array: [_, _, a, b, c, _, _, _, _, _, _, _]
- - - - - - - - - - - - - - -
capacity: 12
length: 8
arrayOffset: 0
limit: 12
position: 4
remaining: 8
content from array: [a, b, c, d, c, _, _, _, _, _, _, _]