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

问题描述 投票:0回答:6

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

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

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

java arrays programming-languages methods
6个回答
14
投票
public int[] method() {
    int z[] = {1,2,3,5};
    return z;
}

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

int []copy = method();

在此之后

copy
也将引用
z
之前引用的同一个数组。

如果这不是您想要的并且您想创建数组的副本,您可以使用

System.arraycopy
创建副本。


4
投票
int[] x = method();

4
投票

int[] anotherArray = method();

您想制作阵列的另一个物理副本吗?

然后使用

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

1
投票

尝试:-

int arr[]=mymethod();

//caling method it stores in array

public int[] mymethod()
{

   return arr;

}

1
投票

如果要复制数组,可以使用

copyOf()


0
投票

您确定要复制吗?

int[] myArray = method();  // now myArray can be used 
© www.soinside.com 2019 - 2024. All rights reserved.