0

I don't understand exactly how System.arraycopy works. Have simple example:

String[] arr = {"a"};
String[] copyArr = new String[10];
System.arraycopy(arr, 0, copyArr, 0, 1);
System.out.println(Arrays.toString(copy));

I understand it like "copy 1 element from arr starting at [0] to copyArr to position [0]". And this is ok. Now I change it to:

String[] arr = {"a"};
String[] copyArr = new String[10];
System.arraycopy(arr, 1, copyArr, 0, 0);
System.out.println(Arrays.toString(copy));

Since arr.length is 1 and the only index that we can call is [0] I expected that it will throw ArrayIndexOutOfBoundsException but it does not.

So the question is what is the difference between these two lines below and why the first one is possible if there is no element at [1] in src (because its length is 1), this is native method so how it is implemented internally?

System.arraycopy(src, 1, dest, 0, 0);
System.arraycopy(src, 0, dest, 0, 0);

What is interesting when we change it to:

System.arraycopy(src, 2, dest, 0, 0);

there is ArrayIndexOutOfBoundsException (and this case is described in the docs because srcPos+length > src.length).

1
  • Because this is what the documentation says? Or do you want to know why it says that? Commented Nov 3, 2016 at 12:31

2 Answers 2

2

There's a zero-length array at src[1] which you can "copy". There isn't a zero-length array at src[2] so the exception is thrown.

Imagine an array of size 3, and the sub-arrays it contains (sub array sizes shown):

[ 0 ][ 1 ][ 2 ]
[ -----3------]
     [----2---]
          [-1-]
             []

Ditto for the beginning of the array, and every position in between indices.

Sign up to request clarification or add additional context in comments.

2 Comments

it would be great if you can elaborate your answer a bit
Thanks, I would just add that in the arraycopy implementation there is a fragment of code that looks like this if (length==0) { return; } and it can be found in question linked by @FaigB and shows how it is implemented internally
1

Here you are topic

from code it is clear:

// Check if the ranges are valid
if  ( (((unsigned int) length + (unsigned int) src_pos) > (unsigned int) s->length())
   || (((unsigned int) length + (unsigned int) dst_pos) > (unsigned int) d->length()) )   {
  THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.