如何在Java中存储方法返回的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2378756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store an array returned by a method in Java
提问by Mohammad Sepahvand
I want to store the array returned by a method into another array. How can I do this?
我想将方法返回的数组存储到另一个数组中。我怎样才能做到这一点?
public int[] method(){
int z[] = {1,2,3,5};
return z;
}
When I call this method, how can I store the returned array (z) into another array?
调用此方法时,如何将返回的数组 (z) 存储到另一个数组中?
采纳答案by codaddict
public int[] method() {
int z[] = {1,2,3,5};
return z;
}
The above method does not return an array par se, instead it returns a reference to the array. In the calling function you can collect this return value in another reference like:
上述方法不返回数组解析,而是返回对数组的引用。在调用函数中,您可以在另一个引用中收集此返回值,例如:
int []copy = method();
After this copy
will also refer to the same array that z
was refering to before.
此后copy
也将引用z
之前引用的相同数组。
If this is not what you want and you want to create a copy of the array you can create a copy using System.arraycopy
.
如果这不是您想要的并且您想要创建数组的副本,您可以使用System.arraycopy
.
回答by saugata
int[] x = method();
回答by Kannan Ekanath
int[] anotherArray = method();
int[] anotherArray = method();
Do you want to make another physical copy of the array ?
你想制作另一个阵列的物理副本吗?
Then use
然后使用
System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
回答by Laurent K
If you want to duplicate the array, you can use [this API][1]:
如果要复制数组,可以使用[这个API][1]:
http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#copyOf(int[], int)
http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#copyOf(int[], int)
回答by fastcodejava
Are you sure you have to copy?
你确定要复制吗?
int[] myArray = method(); // now myArray can be used
回答by porselvi
Try :-
尝试 :-
int arr[]=mymethod();
//caling method it stores in array
public int[] mymethod()
{
return arr;
}