2

Why the range to be copied does not include the array element at final index?

Example:

class ArrayCopyOfDemo { public static void main(String[] args) { char[] copyFrom = {'d', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd'}; char[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9); System.out.println(new String(copyTo)); } } 

Results: "caffein"

(The range to be copied does not include the array element at index 9 (which contains the character a).

Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Thank you very much for your answers!

5
  • This is pretty consistent with all Java ranges, the starting index is included while the end is not. See also String.substring for instance, etc. etc. Commented Apr 10, 2017 at 14:12
  • Because that's how the method works... docs.oracle.com/javase/7/docs/api/java/util/… Commented Apr 10, 2017 at 14:12
  • 5
    It already tells you why in the link you posted: "Note that the second parameter of the copyOfRange method is the initial index of the range to be copied, inclusively, while the third parameter is the final index of the range to be copied, exclusively." Commented Apr 10, 2017 at 14:13
  • The person asked a question, the person may not understand the documentation, rather than hitting out on them about not knowing the documentation, just explain the solution if any. Commented Apr 10, 2017 at 14:15
  • It also makes it easier to do copyOfRange(source, start, start + length) Commented Apr 10, 2017 at 14:30

2 Answers 2

4

From Arrays.copyOfRange javadoc:

 * @param from the initial index of the range to be copied, inclusive * @param to the final index of the range to be copied, exclusive. 
Sign up to request clarification or add additional context in comments.

Comments

0

The Arrays.copyOfRange method will copy from (i, j-1). Your line should be

char[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 10); 

to include the final character.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.