views:

54

answers:

2

Hello, everyone!

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.rewind();
    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!

+1  A: 

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().

Mark Peters
+1  A: 

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.

Jonathon
You're right! This, indeed, implied different behavior.
java.is.for.desktop