简体   繁体   English

如何摆脱指针?

[英]How to get rid of pointers?

To make my question understandable, I'm using the following example code. 为了使我的问题易于理解,我使用以下示例代码。 The output of this code is 5, while I wanted it to be 3. I'm guessing that B is working as a pointer for A, but I want A to be copied in B initially, and subsequent changes in A should not affect B. 该代码的输出为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]);
}

} }

You need to explicitly create a copy, 您需要显式创建一个副本,

int[] B = Arrays.copyOf(A, A.length);

since int[] is a reference type, so an assignment just copies the reference (basically, pointer). 因为int[]是引用类型,所以赋值仅复制引用(基本上是指针)。

If the array elements themselves are not primitive types, you probably will need a deep-copy, so 如果数组元素本身不是原始类型,则可能需要深度复制,因此

type B[] = new type[A.length];
for(int i = 0; i < A.length; ++i) {
    B[i] = makeCopyOf(A[i]);  
}

where makeCopyOf() should create a sensible copy of a type instance. 其中makeCopyOf()应该创建type实例的明智副本。 If you don't find anything better, type makeCopyOf(type orig) { return orig.clone(); } 如果找不到更好的方法,请type makeCopyOf(type orig) { return orig.clone(); } type makeCopyOf(type orig) { return orig.clone(); } could serve as a fallback. type makeCopyOf(type orig) { return orig.clone(); }可以作为备用。

B is a reference , and as such is analogous to a pointer (with various differences - you can't do arithmetic and it's not a direct memory pointer). B是一个引用 ,因此类似于一个指针(有各种不同-您不能做算术,并且它不是直接内存指针)。

As such, you'll have to create a copy of the structure (the array) that you're referring to. 因此,您必须创建要引用的结构(数组)副本 Note that if you're copying objects, you may need a deep copy . 请注意,如果要复制对象,则可能需要深度复制 You would likely have to do this in a copy constructor (see this article as to why clone() is considered broken ) 您可能必须在复制构造函数中执行此操作(请参阅本文,了解为什么clone()被认为是损坏的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM