Pan Ruochen
Pan Ruochen

Reputation: 2070

ByteBuffer.wrap came out unexpectedly

I used ByteArray to create a new string, but the results came out unexpectedly. Here was my code

void foo(byte[] data, ...)
{
    ByteBuffer byteBuf = ByteBuffer.wrap(data, 0, 15);
    String msg = new String(byteBuf.array());
    Log.i("FOO", String.format("ByteArraySize=%d\t\tMsgLen=%d,%d", data.length, byteBuf.array().length, msg.length()));
}

The length of the byte array is 518400. But the log info shows:

ByteArraySize=518400 MsgLen=518400,518400

rather than

ByteArraySize=518400 MsgLen=15,15

What is wrong?

Upvotes: 1

Views: 856

Answers (2)

cshu
cshu

Reputation: 5944

array() returns the byte array that backs the buffer.

It's the same object. i.e. byteBuf.array() == data

To construct a string with subarray of data, use: String msg = new String(data, 0, 15);

Upvotes: 1

Thomas Kläger
Thomas Kläger

Reputation: 21435

That is the expected result.

According to the JavaDoc from ByteBuffer.wrap():

Wraps a byte array into a buffer.

The new buffer will be backed by the given byte array; that is, modifications to the buffer will cause the array to be modified and vice versa.

And ByteBuffer.array():

Returns the byte array that backs this buffer (optional operation).

Modifications to this buffer's content will cause the returned array's content to be modified, and vice versa.

That means that ByteBuffer.array() will return the very same array that you wrapped with ByteBuffer.wrap().

Upvotes: 1

Related Questions