2016-11-03 45 views
0

我不明白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描述)。

+0

因为这是文件说什么?或者你想知道_为什么这么说? – Tunaki

回答

2

src[1]有一个零长度的数组,你可以“复制”。在src[2]处没有零长度数组,因此引发异常。

想象大小3的阵列,并且它所包含的子阵列(所示的子阵列的尺寸):

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

同上,用于该阵列的开始,并在索引之间的每个位置。

+1

这将是伟大的,如果你可以详细说明你的答案 – sanbhat

+0

谢谢,我只是补充说,在arraycopy实现有一段代码,看起来像这样'if(length == 0){return; }'它可以在@FaigB链接的[question](http://stackoverflow.com/questions/12594046/java-native-method-source-code)中找到,并显示它是如何在内部实现的 – swch

1

这里你topic

从代码很明显:

// 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()); 
} 
相关问题