0

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.

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]);
}

}

iamlegend
  • 169
  • 3
  • 15

2 Answers2

5

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).

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. If you don't find anything better, type makeCopyOf(type orig) { return orig.clone(); } could serve as a fallback.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
2

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).

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)

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440