0

I am working with arrayList data.so I have 4 array list.I have 3 arraylist are fill with data one of as for temporery store arraylist as per selection. my code is below.

            if(App.SubPosition==0){
                if(custList.size()>0)
                    custList1=custList;
            }
            if(App.SubPosition==1){
                if(custList.size()>0)
                    custList2=custList;
            }
            if(App.SubPosition==2){
                if(custList.size()>0)
                    custList3=custList;
            }
            App.SubPosition = position;
            String json = null;
            //custList.clear();
            Log.e("Log","custList1="+custList1.size());
            Log.e("Log","custList2="+custList2.size());
            Log.e("Log","custList3="+custList3.size());
            Log.e("Log","custList3="+custList.size());

            custList.clear();

            Log.e("Log","custList1="+custList1.size());
            Log.e("Log","custList2="+custList2.size());
            Log.e("Log","custList3="+custList3.size());
            Log.e("Log","custList3="+custList.size());

run above code it will display log as per below.

enter image description here

If I clear only custlist then it is also clear to custlist1 arraylist.

why is it happen?

Your answer would be appreciated

Vasant
  • 3,475
  • 3
  • 19
  • 33

3 Answers3

1

You never have multiple lists. You have one list and multiple references to that list.

You can create a copy using

custList1 = new ArrayList<>(custList);

This creates a new ArrayList instance, copying the data.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
f1sh
  • 11,489
  • 3
  • 25
  • 51
1

You are using different names for the same ArrayList. Instead of that, try to do something like:

ArrayList<whatever> copy = new ArrayList<>();
copy.addAll(originalArray);

or

ArrayList<whatever> copy = new ArrayList<>(originalArray);

NOTE: do a new every time you want a "copy", since if you don't, you will be adding every element multiple times and will have a huge array instead of a copy.

dquijada
  • 1,697
  • 3
  • 14
  • 19
0

You should use addAll() method.

if(App.SubPosition==0){
    if(custList.size()>0)
        custList1.addAll(custList);
}
if(App.SubPosition==1){
    if(custList.size()>0)
        custList2.addAll(custList);
}
if(App.SubPosition==2){
    if(custList.size()>0)
        custList3.addAll(custList);
}

You can use clone() as well.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Nongthonbam Tonthoi
  • 12,667
  • 7
  • 37
  • 64