首页 > 解决方案 > Updating one list also updating referenced list in Java

问题描述

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.

标签: java

解决方案


这里的问题是您正在创建两个单独的列表,这是真的。但是列表中的对象是相同的。因此,一旦您通过从任何列表中检索对象进行一些更改,它将更新同一对象的状态。

示例解决方案:

方法一:【推荐】

List<TestClass> clonedist == new ArrayList<>(); //To store the clones
            
for (TestClass temp : originalList){ //Looping through the original list and cloning the each element
     clonedList.add(new TestClass(temp.getName()));//Creating a new TestClass object and adding to the list.Name will be set to the object through it's overloaded constructor. 
}  

注意:这里将通过TestClass的重载构造函数创建新的TestClass对象。简而言之,我没有包含有关更新的 TestClass 的代码。但是您仍然可以创建新对象并通过其相关的 setter 方法或直接调用属性名称来更新它的状态(如果您的代码片段中的访问修饰符属性允许)。

方法2:[clone()方法可能有问题]

有关 clone() 方法的更多详细信息:我应该在 java 中使用 Clone 方法吗?

List<TestClass> clonedist == new ArrayList<>(); //To store the clones
            
for (TestClass temp : originalList){ //Looping through the original list and cloning the each element
     clonedList.add(temp.clone());//cloning the object and adding to the list
}  

推荐阅读