S'il vous plaît me aider à comprendre ce qui suit:Java: CharBuffer "ignore" le décalage du tableau?
créer un CharBuffer
en utilisant CharBuffer.wrapped(new char[12], 2, 10)
(tableau, offset, longueur)
donc j'attendre à ce que le tableau est accessible avec un décalage de 2
et la longueur totale (repos) de 10
. Mais arrayOffset()
renvoie 0
.
Ce que je veux comprendre (et ne peut pas comprendre de JavaDoc) est:
quand
arrayOffset()
n'est pas0
etest-il possible de laisser
CharBuffer
utiliser un tableau avec un décalage "réel" (de sorte que le tableau n'est jamais accessible avant ce décalage)?
Voici un petit cas de test:
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);
}
}
Sortie:
- - - - - - - - - - - - - - -
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, _, _, _, _, _, _, _]
Merci!
Vous avez raison! Ceci, en effet, impliquait un comportement différent. –