1

So i have coded something to test the ByteBuffer wrap function:

byte[] cArr = ..

System.out.println("cArr length is " + cArr.length);

ByteBuffer e = ByteBuffer.wrap(cArr, 0, cArr.length );

System.out.println("e length is " + e.array().length);

ByteBuffer d = ByteBuffer.wrap(cArr, 4, 8 );

System.out.println("d length is " + d.array().length);

This is the output:

cArr length is 12

e length is 12

d length is 12

Why is the length of d still 12 even after wrapping and specifying length 8?

3
  • But you asked for the length of the underlying array.. Commented Mar 12, 2016 at 20:14
  • ahh, I see. I thought that by wrapping, a new array is created everytime. Thx! Commented Mar 12, 2016 at 20:17
  • The Javadoc even states as much: "The new buffer's limit will be set to offset + length." Commented Mar 12, 2016 at 20:20

1 Answer 1

1

Why is the length of d still 12 even after wrapping and specifying length 8?

Literally, because d.array() is cArr.

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. The new buffer's capacity will be array.length, its position will be offset, its limit will be offset + length, and its mark will be undefined. Its backing array will be the given array, and its array offset will be zero.

Take the following snippet:

byte[] arr = new byte[12];
ByteBuffer buf = ByteBuffer.wrap(arr, 4, 8);
System.out.println(buf.array() == arr);

which prints true.

http://ideone.com/bqDdDs

ByteBuffer.wrap does not copy the array, it just creates an object around the specified array which lets you work with the array directly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.