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();
}
}