开发者

Java: CharBuffer "ignores" array offset?

开发者 https://www.devze.com 2023-01-04 09:45 出处:网络
Please help me understand the following: I create a CharBuffer using CharBuffer.wrapped(new char[12], 2, 10) (array, offset, length)

Please help me understand the following:

I create a CharBuffer using CharBuffer.wrapped(new char[12], 2, 10) (array, offset, length)

so I would expect that the array is accessed with an offset of 2 and total (rest) length of 10. But arrayOffset() returns 0.

What I want to understand (and can't figure out from JavaDoc) is:

  • when arrayOffset() is not 0, and

  • is there a possibility to let CharBuffer use an array with "real" offset (so that the array is never accessed before that offset)?

Here is a little test case:

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.rewi开发者_如何学运维nd();
    b.put("abcd");
    printBufferInfo(b);
  }

}

Output:

- - - - - - - - - - - - - - -
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, _, _, _, _, _, _, _]

Thank you!


CharBuffer.wrap(char[], int, int):

Its backing array will be the given array, and its array offset will be zero.

Examining writes to CharBuffer.offset it looks like HeapCharBuffer and StringCharBuffer can both have non-zero arrayOffsets().


You can use the position to achieve similar results, I think. Don't use rewind since this sets the position to 0; use reset instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号