我不明白System.arraycopy的工作原理。有简单的例子:System.arraycopy不会抛出ArrayIndexOutOfBoundsException
String[] arr = {"a"};
String[] copyArr = new String[10];
System.arraycopy(arr, 0, copyArr, 0, 1);
System.out.println(Arrays.toString(copy));
我理解,如 “拷贝1元件从ARR在[0]〜copyArr开始[0]位置”。这没关系。现在,我将其更改为:
String[] arr = {"a"};
String[] copyArr = new String[10];
System.arraycopy(arr, 1, copyArr, 0, 0);
System.out.println(Arrays.toString(copy));
由于arr.length为1,而我们只能调用索引[0]我预计它会抛出ArrayIndexOutOfBoundsException异常,但事实并非如此。
所以问题是这两行之间的区别是什么,以及为什么第一个是可能的,如果在src中没有元素[1](因为它的长度是1),这是本地方法,内部实现?
System.arraycopy(src, 1, dest, 0, 0);
System.arraycopy(src, 0, dest, 0, 0);
,当我们将其更改为有趣的是:
System.arraycopy(src, 2, dest, 0, 0);
有ArrayIndexOutOfBoundsException异常(而这种情况下的文档,因为srcPos +长度> src.length描述)。
因为这是文件说什么?或者你想知道_为什么这么说? – Tunaki