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,337
  • 3
  • 17
  • 32

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
  • 131,952
  • 11
  • 151
  • 228
f1sh
  • 10,458
  • 3
  • 23
  • 49
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,584
  • 3
  • 14
  • 21
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
  • 151,199
  • 17
  • 111
  • 216
Nongthonbam Tonthoi
  • 11,939
  • 6
  • 33
  • 61