Can anyone explain me the logic behind strange behavior of Arrays.copyOfRange(byte[], int, int))? I can illustrate what I mean with simple example:
byte[] bytes = new byte[] {1, 1, 1};
Arrays.copyOfRange(bytes, 3, 4); // Returns single element (0) array
Arrays.copyOfRange(bytes, 4, 5); // Throws ArrayIndexOutOfBoundsException
In both cases I copy ranges outside of array boundaries (i.e. start >= array.length
), so the condition for error is at least strange for me (if from < 0
or from > original.length
). In my opinion it should be: if from < 0
or from >= original.length
. Maybe I'm missing something?
copyOfRange(short[] original, int from, int to) method copies the specified range of the specified array into a new array. The final index of the range (to), which must be greater than or equal to from, may be greater than original.
copyOfRange() in Java. This method creates a copy of elements, within a specified range of the original array. to_end : the final index of the range to be copied, exclusive. (This index may lie outside the array.)
The JavaDoc specifies three points regarding the arguments it expects:
One:
[from] must lie between zero and original.length, inclusive
Two:
[to] must be greater than or equal to from
Three:
[to] may be greater than original.length
For the case of Arrays.copyOfRange(bytes, 3, 4)
one, two and three are true which means they are valid.
For the case of Arrays.copyOfRange(bytes, 4, 5)
only two and three are true which means they are invalid.
Expected behaviour? Yes.
Unintuitive behaviour? Kinda.
If your question is secretly "why was it designed this way?" then no one can tell you the answer except the code authors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With