如何在Java中存储方法返回的数组
我想将一个方法返回的数组存储到另一个数组中。我该怎么做如何在Java中存储方法返回的数组,java,arrays,programming-languages,methods,Java,Arrays,Programming Languages,Methods,我想将一个方法返回的数组存储到另一个数组中。我该怎么做 public int[] method(){ int z[] = {1,2,3,5}; return z; } 调用此方法时,如何将返回的数组(z)存储到另一个数组中?int[]anotherArray=method() int[] x = method(); 是否要制作阵列的另一个物理副本 然后使用 System.arraycopy(Object src, int srcPos, Object dest, int
public int[] method(){
int z[] = {1,2,3,5};
return z;
}
调用此方法时,如何将返回的数组(z)存储到另一个数组中?int[]anotherArray=method()
int[] x = method();
是否要制作阵列的另一个物理副本
然后使用
System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
如果要复制阵列,可以使用[此API][1]:
,int)您确定要复制吗
int[] myArray = method(); // now myArray can be used
以上方法不返回数组PAR,而是返回对数组的引用。在调用函数中,您可以在另一个引用中收集此返回值,如:
int []copy = method();
在此之后,copy
还将引用以前引用的z
相同数组
如果这不是您想要的,并且您想创建阵列的副本,则可以使用System.arraycopy
创建副本,尝试:-
int arr[]=mymethod();
//caling method it stores in array
public int[] mymethod()
{
return arr;
}
您是指复制数组,还是仅将此方法的结果赋给一个变量以便使用它?您是指将结果附加到另一个数组上?如中所示,您从foo={9,9,9}开始,然后在调用您的方法之后,希望将它们附加到foo,以便foo成为{9,9,9,1,2,3,5}?非常感谢,int[]x=method();非常好,谢谢。这同样有效吗?int[]x;x=method():欢迎来到Stackoverflow!没有必要重复其他答案。特别是在两年前回答的一个问题上。
int arr[]=mymethod();
//caling method it stores in array
public int[] mymethod()
{
return arr;
}