为了使我的问题可以理解,我使用以下示例代码.这段代码的输出是5,而我希望它是3.我猜测B是作为A的指针,但是我希望A最初在B中复制,而A中的后续更改不应该影响B .
import java.io.*;
public class fg
{
public static void main(String args[]) throws Exception
{
int[] A = new int[3];
A[0]=1;
A[1]=3;
A[3]=7;
check(A);
}
public static void check(int[] A)
{
int[] B = A;
A[1] = 5;
System.out.println(B[1]);
}
Run Code Online (Sandbox Code Playgroud)
}
你需要明确地创建一个副本,
int[] B = Arrays.copyOf(A, A.length);
Run Code Online (Sandbox Code Playgroud)
因为int[]是引用类型,所以赋值只是复制引用(基本上是指针).
如果数组元素本身不是基本类型,那么您可能需要深层复制
type B[] = new type[A.length];
for(int i = 0; i < A.length; ++i) {
B[i] = makeCopyOf(A[i]);
}
Run Code Online (Sandbox Code Playgroud)
makeCopyOf()应该在哪里创建一个合理的type实例副本.如果你没有找到更好的东西,type makeCopyOf(type orig) { return orig.clone(); }可以作为后备.
| 归档时间: |
|
| 查看次数: |
156 次 |
| 最近记录: |