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