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

swch
  • 1,432
  • 4
  • 21
  • 37

2 Answers2

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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • 1
    it would be great if you can elaborate your answer a bit – sanbhat Nov 03 '16 at 12:26
  • 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](http://stackoverflow.com/questions/12594046/java-native-method-source-code) linked by @FaigB and shows how it is implemented internally – swch Nov 03 '16 at 12:46
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());
}
Community
  • 1
  • 1
FaigB
  • 2,271
  • 1
  • 13
  • 22