After looking into the source of Arrays.copyOfRange(byte[] original, int from, int to)
public static byte[] copyOfRange(byte[] original, int from, int to) {
1 int newLength = to - from;
2 if (newLength < 0)
3 throw new IllegalArgumentException(from + " > " + to);
4 byte[] copy = new byte[newLength];
5 System.arraycopy(original, from, copy, 0,
6 Math.min(original.length - from, newLength));
7 return copy;
}
- at line 1 the length of the destination array is computed with
1
- at line 4 the new array is created with size
1
, all elements are 0
at line 6 the length of the element to be copied is computed as zero, because
// Math.min(original.length - from, newLength));
Math.min(3 - 3, 1)); --> returns zero
- at line 5 the
System.arraycopy
simply does not copy anything into array copy
If your from
is bytes.length + 1
then length
get negative (bytes.length - from).
A small code to demonstrate
public class ArrayCopy {
public static void main(String[] args) {
byte[] bytes = new byte[]{11, 12, 13};
int from = 3;
int to = 4;
copyOfRange(bytes, from, to);
from = 2;
to = 3;
copyOfRange(bytes, from, to);
from = 4;
to = 5;
copyOfRange(bytes, from, to);
}
static void copyOfRange(byte[] bytes, int from, int to) {
System.out.printf("%ncopyOfRange(bytes: %s from: %d to: %d)%n",
Arrays.toString(bytes),
from,
to
);
// line 1
int newLength = to - from;
System.out.println("int newLength = " + newLength);
// line 2
if (newLength < 0) {
throw new IllegalArgumentException(from + " > " + to);
}
// line 4
byte[] copy = new byte[newLength];
// to show that in the suspicious case System.arrayCopy does nothing
copy[0] = 42;
System.out.println("byte[] copy = " + Arrays.toString(copy));
int length = bytes.length - from;
System.out.println("int length = " + length);
int minLenght = Math.min(length, newLength);
System.out.println("int minLenght = " + minLenght);
// line 5
System.arraycopy(bytes, from, copy, 0, minLenght);
System.out.println("byte[] copy = " + Arrays.toString(copy));
}
}
output
copyOfRange(bytes: [11, 12, 13] from: 3 to: 4)
int newLength = 1
byte[] copy = [42]
int length = 0
int minLenght = 0
byte[] copy = [42]
copyOfRange(bytes: [11, 12, 13] from: 2 to: 3)
int newLength = 1
byte[] copy = [42]
int length = 1
int minLenght = 1
byte[] copy = [13]
copyOfRange(bytes: [11, 12, 13] from: 4 to: 5)
int newLength = 1
byte[] copy = [42]
int length = -1
int minLenght = -1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException