Eric
Eric

Reputation: 373

Trying to find out why setting an object equal to another updates both objects

Example Code

public class test {
    
    public test(){
        runTest();
    }
    
    private void runTest(){

//method 1
        int[] A = {1,2,3,4};
        int[] B = new int[A.length];        
        for (int i = 0; i < A.length; i++){
            B[i] = A[i]+1;
        }
        for (int i: A){
            System.out.println(" A: " + i);
        }
        System.out.println("----------");

        for (int i: B){
            System.out.println(" B: " + i);
        }
        System.out.println("----------");



//method 2                
        int[] C = {1,2,3,4};
        int[] D = C;
        for (int i = 0; i <D.length; i++){
            D[i]++;
        }
        for (int i: C){
            System.out.println(" C: " + i);
        }
        System.out.println("----------");

        for (int i: D){
            System.out.println(" D: " + i);
        }
        System.out.println("----------");

        
        
    }
    
    public static void main(String[] args){
        new test();
    }
}

Question

I was running into an issue in one of my methods and found the issue was creating the temporary object altered the original, which I did not want to happen. I was just wondering why this occurs, I was under the impression that setting an object equal to another only points it to that current location/state, not any future updates.

In other words, wanted to know why I have do what I did with int A and int B instead of doing what I did with int C and int D.

To make it even simpler, what is the difference between the two methods above? I'm going to take a stab at it and say the JVM calls the same reference when either int C or int D is called, as I didn't create a new object as I did with the int A int B.

Upvotes: 0

Views: 56

Answers (1)

rgettman
rgettman

Reputation: 178323

The difference is that with A and B, B is a copy of the array and a completely separate object from A. With C and D, D is another array reference that refers to the same object as C. D continues to refer to not just the "that current location/state", but that same object, until it is reassigned or it goes out of scope. Whatever you do to the object referred to by D will be visible through C as well, as it is the same object.

Upvotes: 1

Related Questions