0

Can someone explain why my expected and actual results are different.

I have already gone through some other posts in various sites (including stackoverflow) but answers are not cut to point.

public class Test 
{
    List<String> str= new ArrayList<String>();      

    public void addString(String a)
    {
        str.add(a);
    }

    public void takeALocalCopy(Test c)
    {
        Test localCopy1= c;
        localCopy1.addString("Two");

        //Expecting output -->One,Two   -->Success.
        System.out.println(localCopy1.toString());

        Test localCopy2= c;
        localCopy2.addString("Three");

        //Expecting -->One,Three  but actual is One,Two,Three.      
        System.out.println(localCopy2.toString());  
    }

    @Override
    public String toString() {
        return "Test [str=" + str + "]";
    }       

    public static void main(String[] args) 
    {
        Test c= new Test();
        c.addString("One");
        c.takeALocalCopy(c);        
    }
}

OUTPUT:

Test [str=[One, Two]]
Test [str=[One, Two, Three]]  //Expected One, Two
mdewitt
  • 2,526
  • 19
  • 23
madhu_karnati
  • 785
  • 1
  • 6
  • 22

1 Answers1

0

Although you called it ..Copy.., I think you misunderstand what you are copying. The value stored in reference type variables is a reference to an object. So what you are copying is that reference value, not the object.

You created a single instance of type Test in your application, the one in the main method

Test c= new Test();

You then passed around the value of the reference stored in c. Each other usage of that value is still referencing the same object.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Can you explain me clearly , your statement. "So what you are copying is that reference value, not the object". – madhu_karnati Oct 01 '14 at 22:35
  • @madhureddy480 When you do `Object o = new Object()`, what is stored in `o` is actually an address to the instance created. When you use `o` in as an argument in a method invocation, Java copies its value (the value of the address) and binds it to the corresponding method parameter. – Sotirios Delimanolis Oct 01 '14 at 22:37