swch swch - 1 year ago 87
Java Question

System.arraycopy does not throw ArrayIndexOutOfBoundsException

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

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

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

Answer Source

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------]

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download