2013-05-08 40 views
1

我有一個名爲「第一個」的數組和另一個名爲「第二個」的數組,這兩個數組的字節類型和大小爲10個索引。Java:System.arraycopy不復制我的陣列

我複製兩個陣列成一個陣列稱爲類型字節的「第三」太和長度爲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

這個循環是不必要的,如果你使用'arraycopy'。反過來說,如果你使用循環,'arraycopy'不是必需的,因爲你自己分配值。 – Gamb 2013-05-08 15:40:34

回答

9

你通過System.arraycopy數組,而不是數組元素。通過傳遞first[i]arraycopy作爲第一個參數,你在一個byte,它(因爲arraycopy被聲明爲接受Objectsrc參數)將被提升到Byte。所以,你要ArrayStoreException在列表中的第一個原因在the documentation

...如果有下列情況爲真,一個ArrayStoreException拋出和不修改目標:

src參數指的是一個不是數組的對象。

這裏是你如何使用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); 
+0

感謝大家..但我決定接受這個答案,以解釋我的錯誤.. – 2013-05-08 17:00:18

2
System.arraycopy(first, 0, third, 0, first.length); 
System.arraycopy(second, 0, third, first.length, second.length);