【问题标题】:Java: CharBuffer "ignores" array offset?Java:CharBuffer“忽略”数组偏移量?
【发布时间】:2010-06-21 15:45:05
【问题描述】:

请帮助我理解以下内容:

我创建了一个CharBuffer 使用 CharBuffer.wrapped(new char[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);
  }

}

输出:

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

谢谢!

【问题讨论】:

    标签: java arrays buffer nio


    【解决方案1】:

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

    它的后备数组将是给定的数组,它的数组偏移量为零。

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-24
        • 1970-01-01
        • 2017-12-17
        • 2016-02-11
        • 2012-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多