There is a class Model1, which contains some parameters and List.

List<Model1> Class Model1: private String param1; private String param2; private List<Model2> param3List= new ArrayList<>(); 

I load server data, set it into a fragment

 public void setServices(List<Model1> model1) { this.modelList1.clear(); this.modelList1.addAll(model1); } 

Next, I check this data and add param3List to the adapter.

 list.clear(); for (Model2 m2 : modelList1) { list.addAll(m2.getParam3List()); adapter.notifyDataSetChanged(); break; } 

And for some unknown reason, once list.clear () clears only the sheet that is in the adapter, and another time clears the sheet that is in the adapter and with it param3List, which is in modelList1.

  • Nothing is clear. Give a more detailed procedure. At the moment, of the separate pieces of code, what's the problem to make a presentation is difficult. - Yuriy SPb
  • There is a list of payments, there is the possibility of re-payment and the ability to create a payment, if after downloading this list try to make a second payment, which is already on the list, everything is normal, all payment parameters are loaded and nothing is cleared, and if you create a payment and then try to repay it again, then all the data is loaded into the list of payment parameters, except for the list data described above, that's when it is cleared, for some reason - 5mi13
  • Few details, and your clarifications are hardly relevant. You either have a problem in the architecture, or you assign a link object somewhere instead of using the old one. Little code - just guesses. - YurySPb
  • I suppose that the links point to the same List for example. Considering that in the set method you do not make a normal set , but actually add an element to the same list, clearing it ... Are there any reasons why this is exactly how it is implemented? - iksuy
  • one
    Why clean an existing list if you can just assign a new one? Why not write this.modelList1 = model1 ? - iksuy

1 answer 1

A list is an object in memory. It can be referenced by one or more variable references.

When you want to work with one list from different variables you assign it once to different links. In this case, through any variable you can clear this list.

If you need to have different, independent lists in different variables, then you need to create different objects.

 List<Model2> someList = new ArrayList<>(); List<Model2> sameList = someList; //тот же объект. изменения в нём отразятся на someList List<Model2> anotherList = new ArrayList<>(sameList); //новый объект. //изменения этого объекта не отразятся на someList и sameList 
  • Well, I did, and the changes are still reflected in it - 5mi13
  • @ 5mi13, try the updated code. And make sure that you do not reassign the link to the list anywhere. - YurySPb
  • Thanks, I will try this option. If it does not work out, I will unsubscribe. - 5mi13