gpt4 book ai didi

java - System.arraycopy 不会抛出 ArrayIndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-12-01 21:14:54 24 4
gpt4 key购买 nike

我不明白 System.arraycopy 是如何工作的。举个简单的例子:

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

我理解它就像“从 [0] 开始的 arr 复制 1 个元素到 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),第一行是可能的,这是 native 方法,所以它是如何的内部实现?

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

当我们将其更改为时,有趣的是:

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

存在 ArrayIndexOutOfBoundsException(文档中描述了这种情况,因为 srcPos+length > src.length)。

最佳答案

src[1] 处有一个零长度数组,您可以“复制”它。 src[2] 处不存在零长度数组,因此会引发异常。

想象一个大小为 3 的数组及其包含的子数组(显示子数组大小):

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

数组的开头以及索引之间的每个位置也是如此。

关于java - System.arraycopy 不会抛出 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40401303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com