我有一个名为“first”的数组和另一个名为“second”的数组,两个数组都是字节类型,大小为 10 个索引。
我正在将这两个数组复制到一个名为“third”的字节类型数组中,长度为 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 数组中时,将抛出此异常。但是我所有的数组都是以字节为单位的,所以没有不匹配
到底是什么问题?
最佳答案
你通过了System.arraycopy
数组,而不是数组元素。通过将 first[i]
作为第一个参数传递到 arraycopy
中,您传递了一个 byte
,它(因为 arraycopy
被声明为接受 Object
作为 src
参数)被提升为 Byte
。因此,由于 the documentation 列表中的第一个原因,您将获得 ArrayStoreException
:
...if any of the following is true, an
ArrayStoreException
is thrown and the destination is not modified:The
src
argument refers to an object that is not an array.
下面是如何使用 arraycopy
将两个 byte[]
数组复制到第三个数组中:
// Declarations for `first` and `second` for clarity
byte[] first = new byte[10];
byte[] second = new byte[10];
// ...presumably fill in `first` and `second` here...
// Copy to `third`
byte[] third = new byte[first.length + second.length];
System.arraycopy(first, 0, third, 0, first.length);
System.arraycopy(second, 0, third, first.length, second.length);
关于Java:System.arraycopy 没有复制我的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16444684/