2010-06-21 10 views
1

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 pas 0 et

  • est-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!

Répondre

1

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

Son tableau de sauvegarde sera le tableau donné, et son tableau de décalage sera égal à zéro.

écrit à CharBuffer.offset il examen ressemble HeapCharBuffer et StringCharBuffer peuvent tous les deux ont non nuls arrayOffsets().

1

Vous pouvez utiliser le position pour obtenir des résultats similaires, je pense. N'utilisez pas rewind car cela définit position sur 0; utilisez reset à la place.

+0

Vous avez raison! Ceci, en effet, impliquait un comportement différent. –