0

なぜこれが機能しないのですか?

tt のバッキング配列を調べると、すべての値が 0 であるのに対し、bb は 1 ~ 100 のシーケンスです。また、system.out が最後に同一ではないのはなぜですか?

ByteBuffer bb = ByteBuffer.allocateDirect(100);
for(int i =0;i< 100; i++) {
  bb.put(new Byte(""+i));
}
ByteBuffer tt = ByteBuffer.allocateDirect(100);
tt.put(bb);

for(int i =0;i< 100; i++) {
       System.out.println("BACKED bb" + bb.get(i));
       System.out.println("BACKED tt" + tt.get(i));
}
4

2 に答える 2

5

問題は、put(byte)が現在の位置をインクリメントするためbb、結果をに読み込もうとするttと、バッファの最後から読み取られることです。

やりたいことをするには、次のようなものが必要です。

ByteBuffer bb = ByteBuffer.allocateDirect(100);
for(int i =0;i< 100; i++) {
  bb.put((byte)i);
}
ByteBuffer tt = ByteBuffer.allocateDirect(100);
// reset the position so that we can copy it to the new ByteBuffer.
// Could also call bb.rewind() here. 
bb.position(0);
tt.put(bb);

for(int i =0;i< 100; i++) {
       System.out.println("BACKED bb" + bb.get(i));
       System.out.println("BACKED tt" + tt.get(i));
}

余談ですが、作成を少し変更しました。バイト値を取得するために文字列を作成する必要はなく、int を直接バイトにキャストするだけです。

于 2013-10-23T23:37:35.207 に答える
-2

これを試しましたか:

bb.put((new Byte(""+i)).byteValue());
于 2013-10-23T23:42:49.707 に答える