I am facing strange problem (At least awkward for me). I have a list of custom objects. I am adding this list of custom objects 2 other ArrayLists. Here is the problem, when I update one of the list (a property of any custom object), it updates the object of same location in other list. Below is the code
Below is the custom class for example:
public class TestClass {
String name;
}
Here is how I am creating data set:
TestClass testClass1 = new TestClass();
testClass1.name= "first";
TestClass testClass2 = new TestClass();
testClass2.name= "second";
List<TestClass> data = new ArrayList<>();
data.add(testClass1);
data.add(testClass2);
Here is how I am adding data set in other 2 Lists:
List<TestClass> testListFirst = new ArrayList<>();
testListFirst.addAll(data);
List<TestClass> testListSecond = new ArrayList<>();
testListSecond.addAll(data);
Here is the problem when I update an element of one list it gets updated in second list as well:
testListFirst.get(0).name = "third";
If I check testListFirst it is updated with new value, but testListSecond is also updated. My expectation was testListSecond It should not get updated because they both list are different object in memory pointing different objects. If I update one other should not be updated. Please correct me if I am wrong. Any help is highly appreciated.