我有一个名为“first”的数组和另一个名为“second”的数组,两个数组都是byte类型和10个索引的大小。
我将两个数组复制到一个名为“third”的数组中,类型为byte,长度为2 * first.length,如下所示:
byte[] third= new byte[2*first.length];
for(int i = 0; i<first.length;i++){
System.arraycopy(first[i], 0, third[i], 0, first.length);
}
for(int i = 0; i<second.length;i++){
System.arraycopy(second[i], 0, third[i], first.length, first.length);
}
但它没有复制,它抛出异常:ArrayStoreException
我在here上读到当src数组中的元素由于类型不匹配而无法存储到dest数组时抛出此异常。但我的所有数组都以字节为单位,因此没有不匹配
究竟是什么问题?
答案 0 :(得分:9)
您传递了System.arraycopy
数组,而不是数组元素。通过将first[i]
作为第一个参数传递给arraycopy
,您传递的是 byte
,因为arraycopy
被声明为接受{对于Object
参数,{1}}会被提升为src
。因此,the documentation列表中的第一个原因是Byte
:
...如果满足以下任何条件,则抛出
ArrayStoreException
并且不修改目的地:
ArrayStoreException
参数指的是不是数组的对象。
以下是使用src
将两个arraycopy
数组复制到第三个数组的方法:
byte[]
答案 1 :(得分:2)
System.arraycopy(first, 0, third, 0, first.length);
System.arraycopy(second, 0, third, first.length, second.length);