Java:当'src.length = 5'时,为什么'System.arraycopy(src,5,dst,0,0)'没有抛出超出范围的异常?

问题描述 投票:-1回答:1

所以,首先我声明了这两个数组:

int[] num = {50,20,30,40};
int[] num2 = new int[8];

现在我尝试了此代码:

System.arraycopy(num, 0, num2, 0, 4);

我知道这会将整个'num'数组复制到'num2'数组的前四个索引中,并且将'System.arraycopy()'方法的'length'参数增加到大于'4'抛出“ ArrayIndexOutOfBoundsException”异常,很简单!

但是,我没有得到,为什么下面的代码是:

//Snippet 1
System.arraycopy(num, 4, num2, 0, 0);

有效,当'num'的最大索引仅为3时?

而且,如果代码段1是有效的,那么为什么是以下原因:

//Snippet 2
System.arraycopy(num, 5, num2, 0, 0);

无效,是否抛出上面引用的异常?此外,为什么是:

//Snippet 3
System.arraycopy(num, 4, num2, 0, 1);

也无效?

谈论Java文档,它提到:

// 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());
}

// Special case. Boundary cases must be checked first
// This allows the following call: copy_array(s, s.length(), d.length(), 0).
// This is correct, since the position is supposed to be an 'in between point', i.e., s.length(),
// points to the right of the last element.
if (length==0) {
  return;
}

现在,我知道我将从中得到答案。但是,我真正要理解的是:为什么对于'src_pos'和'dst_pos'参数,我可以从's'和'd'数组中提及一个有效的索引,还可以提及'假设我将'length'参数保持为'0',则是s.length'或'd.length'吗?或者只是为什么在文档中提到了这种情况:

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

像这样(像这样使用它)而不像这样:

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

此?

谢谢您的时间:)

java arrays indexoutofboundsexception
1个回答
0
投票
System.arraycopy(num, 4, num2, 0, 0); // valid because nothing is to be copied
System.arraycopy(num, 4, num2, 0, 1); // exception because you try to copy ONE element from pos. 4 of num which is non-existent

希望您可以看到长度0(无副本)和1(一个元素)之间的差异

© www.soinside.com 2019 - 2024. All rights reserved.