[英]Created two Lists from same pojo array, Modifying one List, same thing affects on other list also
I have created two lists object from the same pojo and sorted one of them. 我从同一个pojo创建了两个列表对象,并对其中之一进行了排序。 When I tried to change one list, other lists also got updated.
当我尝试更改一个列表时,其他列表也得到了更新。
List<FilterPojo.Data> filterList = new ArrayList<>();
List<FilterPojo.Data> subFilterList = new ArrayList<>();
If I change the value in filterList
, same changes occur in subFilterList
如果我更改值
filterList
,发生同样的变化subFilterList
With the limited information that is provided by you, it seems you are creating/populating subFilterList
as subList
of filterList
. 使用您提供的有限信息,您似乎正在将
subFilterList
创建/填充为subList
的filterList
。 When you do that, all changes made in either of the list will be reflected in other. 当您这样做时,在任一列表中所做的所有更改都将反映在其他列表中。
This happens because List.subList()
, returns a view of the list, so modifications to the original list will be reflected in the sub-list. 发生这种情况是因为
List.subList()
返回列表的视图,因此对原始列表的修改将反映在子列表中。 As suggested by others, instead of subList
use addAll
to populate subFilterList
如其他人所建议的,而不是
subList
使用addAll
填充subFilterList
This could be reference problem. 这可能是参考问题。 Lists maintains their references when items are copied to other list, if you do something like:
将项目复制到其他列表时,列表会保留其引用,如果您执行以下操作:
List<FilterPojo.Data> subFilterList = filterList;
Use addAll
method instead, 请改用
addAll
方法,
subFilterList.clear();
subFilterList.addAll(filterList);
I don't know exactly the context that you are asking. 我不完全了解您所要求的背景。
Your lists are holding the same object. 您的列表包含相同的对象。 For example, in this case p1.
例如,在这种情况下为p1。
Person p1 = new Person();
List<Person> list1 = new ArrayList<Person>();
list1.add(p1);
List<Person> list2 = new ArrayList<Person>();
list2.add(p1);
p1.setName("new name");
Try below 试试下面
List<String> filterList = new ArrayList<String>();
List<String> subFilterList = new ArrayList<String>();
filterList.add("A");
filterList.add("B");
filterList.add("C");
/*subFilterList = filterList; // reference to same object , change will reflect in both
filterList.add("C");
System.out.println(filterList);
System.out.println(subFilterList);*/
subFilterList.addAll(filterList);
filterList.add("C");
System.out.println(filterList);
System.out.println(subFilterList);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.