sangavi
sangavi

Reputation: 441

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. 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

Upvotes: 0

Views: 82

Answers (4)

irfan
irfan

Reputation: 896

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);

Upvotes: 1

Nttrungit90
Nttrungit90

Reputation: 68

I don't know exactly the context that you are asking.
Your lists are holding the same object. For example, in this case 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");

Upvotes: 0

Ashishkumar Singh
Ashishkumar Singh

Reputation: 3600

With the limited information that is provided by you, it seems you are creating/populating subFilterList as subList of 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. As suggested by others, instead of subList use addAll to populate subFilterList

Upvotes: 2

sneharc
sneharc

Reputation: 513

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,

subFilterList.clear();
subFilterList.addAll(filterList);

Upvotes: 1

Related Questions