java - 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.
解决方案
这里的问题是您正在创建两个单独的列表,这是真的。但是列表中的对象是相同的。因此,一旦您通过从任何列表中检索对象进行一些更改,它将更新同一对象的状态。
示例解决方案:
方法一:【推荐】
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
}
推荐阅读
- javascript - 除了这个,还有更好的方法从 React 中的父组件调用子函数吗?
- laravel - Larvel 刀片未从分页加载所有图像
- javascript - 为什么我的快速删除请求不起作用?
- python - 我收到此错误找不到元素
- tensorflow - 未知:读取 TFRecords 时输入/输出错误
- reactjs - axios 拦截器不发送请求
- python - 如何使用 selenium 在 chrome 的提示中导航
- javascript - 为什么 Bootstrap 图标在 ReactJS 中不起作用?
- java - 我的 Android 示例上的复选框活动显示带有多个文本显示/隐藏选项的错误
- c# - 控制器中的 TempData 为空