2012-04-13 66 views
4

可能重複:
Make copy of array Java如何通過Java中的值複製數組?

我在Java的初學者,我需要一個數組的內容複製到另一個變量。但是,Java總是通過引用而不是按值傳遞數組。

這裏就是我的意思是,如果這是令人困惑:

int test[]={1,2,3,4}; 
int test2[]; 
test2=test; 
test2[2]=8; 
for(int i=0;i<test2.length;i++) 
    System.out.print(test[i]); // Prints 1284 instead of 1234 

在這個例子中,我不希望的test值改變。這可能沒有使用任何Java的更高級功能,如ArrayList和Vectors?

編輯:我試過System.ArrayCopy和test.clone(),但他們似乎仍然沒有工作。 這裏是我的實際代碼:

temp_image=image.clone(); 
for(int a=0;a<image.length;a++) 
    for(int b=0;b<image[0].length;b++) 
     image[a][b]=temp_image[image.length-1-a][b]; 

基本上我試圖翻轉「圖像」倒掛。代碼中有沒有錯誤?

+0

System.arraycopy:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html – 2012-04-13 02:34:12

+0

@LuiggiMendoza你可能要開始使用更多最近的JavaDocs; [Java 1.4是3個版本(10年)](http://en.wikipedia.org/wiki/Java_version_history)。 – 2012-04-13 02:37:08

+0

當然,這有2000個確切的重複嗎? – 2012-04-13 02:43:17

回答

5

你需要克隆你的數組。

test2=test.clone(); 
2

Java 6中開始,你可以使用Arrays.copyOf

test2 = Arrays.copyOf(test, test.length); 

對於你希望做什麼,test.clone()的罰款。但是如果你想做一個調整大小,copyOf可以讓你做到這一點。我認爲在性能方面它

System.arraycopy如果你需要它們會提供更多的選擇。

0

由於測試和測試2都指向同一個數組,你與你的聲明改變着testtest2價值test2[2]=8

一個解決辦法是將測試的內容複製到測試2和改變在test2的特定索引處的值。

for (int i=0,i<test.length,i++) 
     test2[i]=test[i] 
    //Now both arrays have the same values 

    test2[2]=8 

    for (int j=0,j<test.length,j++) 
     System.out.print(test[i]) 
     System.out.println() 
     System.out.print(test2[i]) 

將輸出

1 2 3 4 
    1 2 8 4