Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Why do ByteBuffer.wrap() and ByteBuffer.slice() have the same behavior

skidmarksMar 2 2011 — edited Mar 2 2011
I'm trying to return a slice of an array from a method. I can understand why ByteBuffer.wrap(array, offset, length).array() returns the entire array, the documentation says that it returns the backing array. But I don't understand why this should occur with a slice. In reading the documentation it seemed to me that in a slice after setting the position in a wrapped ByteBuffer, the slice() method would consider the backing array as consisting only of the selected slice. I am doing something wrong and maybe someone can steer me in the correct direction. Code below.
    public class test {
    public static byte[] testWrap() {
        byte[] ar = new byte[20];
        for (int i = 0; i < ar.length; i++) ar[i] = (byte)(i + 1);
        ByteBuffer testByte = ByteBuffer.wrap(ar, 5, ar.length - 5);
        byte[] wrapByte = testByte.array();
        return testByte.array();
    }
    
    public static byte[] testSlice() {
        byte[] ar = new byte[20];
        for (int i = 0; i < ar.length; i++) ar[i] = (byte)(i + 1);
        ByteBuffer testByte = ByteBuffer.wrap(ar);
        testByte.position(5);
        ByteBuffer slice = testByte.slice();
        byte[] wrapByte = slice.array();
        return slice.array();
    }
    static void main(String... argv) {
       byte[] wrap = testWrap();
       byte[] slice  = testSlice();
    }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 30 2011
Added on Mar 2 2011
6 comments
1,237 views