如何在Java中存储由方法返回的数组

我想将方法​​返回的数组存储到另一个数组中。 我怎样才能做到这一点?

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

当我调用此方法时,如何将返回的数组(z)存储到另一个数组中?

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

上面的方法不会返回数组,而是返回对数组的引用。 在调用函数中,您可以在另一个引用中收集此返回值,如:

 int []copy = method(); 

copy之后还将引用z之前引用的相同数组。

如果这不是您想要的,并且您想要创建arrays的副本,则可以使用System.arraycopy创建副本。

int [] anotherArray = method();

你想制作arrays的另一个物理副本吗?

然后用

 System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) 
 int[] x = method(); 

如果要复制数组,可以使用[this API] [1]:

http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#copyOf(int [] ,int)

尝试: –

 int arr[]=mymethod(); //caling method it stores in array public int[] mymethod() { return arr; } 

你确定要复制吗?

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