2

I tried all way but always it is referencing the previous one.

mListPreviousData = new ArrayList<>();
for (int i = 0; i < mAddedList.size(); i++) {
    mListPreviousData.add(mAddedList.get(i));
}
K Neeraj Lal
  • 6,768
  • 3
  • 24
  • 33
UserSharma
  • 458
  • 6
  • 20
  • just do mListPreviousData = (ArrayList) mAddedList.clone(); You need to cast in to your arraylist type – Divyang Panchal Feb 03 '17 at 09:53
  • 1
    type of both arrayList is same that's why it is referencing the previous one – UserSharma Feb 03 '17 at 09:55
  • You can use [this](https://github.com/google/guava) library or by constructor you can get **shallow** copy. – DwlRathod Feb 03 '17 at 09:55
  • Possible duplicate of [How do I copy the contents of one ArrayList into another?](http://stackoverflow.com/questions/8441664/how-do-i-copy-the-contents-of-one-arraylist-into-another) – Ankush Bist Feb 03 '17 at 10:01
  • If you do not want to create two separate list by cloning your list object , Then you need to create Data List Item Each time within loop and then add into your mListPreviousData list .Meas you need to create new object each time. – Chetan Joshi Feb 03 '17 at 10:54

2 Answers2

2

You need to make a deep copy of the underlying objects:

mListPreviousData = new ArrayList<>();
for (int i = 0; i < mAddedList.size(); i++) {
    mListPreviousData.add(mAddedList.get(i).clone());
}

Preferably, you implement your own clone() method.

Edit:

Or do a deep copy of the entire arraylist:

mListPreviousData = (..cast to your type..) mAddedList.clone();
Tobias G
  • 583
  • 2
  • 10
  • drawback if the original list data is changed the cloned copy will automatically updated – Ankush Bist Feb 03 '17 at 09:59
  • same thing i don't want i need two separate lists. – UserSharma Feb 03 '17 at 10:02
  • If you do not want to create two separate list by cloning your list object , Then you need to create Data List Item Each time within loop and then add into your mListPreviousData list .Meas you need to create new object each time – Chetan Joshi Feb 03 '17 at 10:55
1
mListPreviousData = new ArrayList<>(); 
mListPreviousData.addAll(mAddedList);
Bishu
  • 82
  • 1
  • 7