2010-03-04 45 views
6

我想將方法​​返回的數組存儲到另一個數組中。我怎樣才能做到這一點?如何存儲Java中的方法返回的數組

public int[] method(){ 
    int z[] = {1,2,3,5}; 
    return z; 
} 

當我調用此方法時,如何將返回的數組(z)存儲到另一個數組中?

+0

你的意思是複製陣列,或者只是這種分配方法的結果給一個變量,所以你可以使用它? – extraneon

+0

你的意思是將結果附加到另一個數組上嗎?和你一樣,你從foo = {9,9,9}開始,然後在調用你的方法之後,你想把它們追加到foo,使得foo變成{9,9,9,1,2,3,5}? – Douglas

回答

13
public int[] method() { 
    int z[] = {1,2,3,5}; 
    return z; 
} 

上述方法不返回的數組帕本身,而不是將其返回到數組的引用。在調用函數你可以像其他引用收集這些返回值:

int []copy = method(); 

在此之後copy也將指向同一個數組z是指的面前。

如果這不是你想要的,你想創建一個數組副本,你可以使用System.arraycopy創建一個副本。

3
int[] x = method(); 
+0

非常感謝,int [] x = method();非常感謝,謝謝。 –

4

int [] anotherArray = method();

你想製作另一個數組的物理副本嗎?

然後使用

System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) 
+0

爲什麼不只是.clone()? – Ingo

0

你確定你要複製?

int[] myArray = method(); // now myArray can be used 
+1

想知道我們是否可以在這裏使用for循環? –

1

嘗試: -

int arr[]=mymethod(); 

//caling method it stores in array 

public int[] mymethod() 
{ 

    return arr; 

} 
+1

歡迎來到Stackoverflow!沒有必要重複其他答案。特別是在2年前回答的問題上。 –