2010-11-23 73 views
0

將兩個陣列複製到新陣列中的最佳方式(優雅/高效)是什麼?將新陣列複製到新陣列中

問候,

˚F

+0

你至少應該嘗試發佈提問.. – posdef 2010-11-23 10:14:22

+0

爲什麼下投票前搜索一下呢? stackoverflow回答必須處理編程的問題 – Tyzak 2010-11-23 10:54:44

回答

0

使用System.arraycopy需要底層硬件的優點在於儘可能有效地執行的陣列副本。

在問題的背景下,您需要撥打System.arraycopy兩次;例如

int[] dest = new int[10]; 
int[] src1 = new int[5]; 
int[] src2 = new int[5]; 

// Populate source arrays with test data. 
for (int i=0; i<5; ++i) { 
    src1[i] = i; 
    src2[i] = i + 100; 
} 

System.arraycopy(src1, 0, dest, 0, src1.length); 
System.arraycopy(src2, 0, dest, src1.length, src2.length); 
5

我的名譽不允許我對亞當斯基的回答發表評論,但在這條線的錯誤:

System.arraycopy(src2, 0, dest, src1.length - 1, src2.length); 

隨着src1.length - 1作爲參數傳遞給destPos,則覆蓋從SRC1陣列中複製的最後一個元素。在這種情況下,您將覆蓋索引4上的元素,該索引是數組的第5個元素。

此代碼可能會更容易理解:

int[] array1 = { 1, 2, 3 }; 
    int[] array2 = { 4, 5, 6, 7 }; 
    int[] array3 = new int[ array1.length + array2.length ]; 

    System.arraycopy(array1, 0, array3, 0, array1.length); 
    System.arraycopy(array2, 0, array3, array1.length, array2.length); 

    for (int i = 0; i < array3.length; i++) { 
     System.out.print(array3[i] + ", "); 
    }