Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the logic behind Arrays.copyOfRange(byte[], int, int) strange behavior?

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?

like image 480
Ivan Sharamet Avatar asked Sep 08 '17 07:09

Ivan Sharamet


People also ask

What does Arrays copyOfRange do?

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.

What does copyOfRange do in Java?

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.)


1 Answers

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.

like image 66
Michael Avatar answered Oct 10 '22 21:10

Michael