-1

I tried like below. I want to copy one array list of jsonobject to another without referencing to same...., Can anyone explain me what i am doing wrong??

ArrayList<JSONObject> a = new ArrayList<JSONObject>();
JSONObject aa = new JSONObject();
aa.put("key1", "old");
aa.put("key2", "old");
aa.put("key3", "old");
a.add(aa); `T`

ArrayList<JSONObject> b = new ArrayList<JSONObject>();
b = a; 
b.get(0).put("key1", "new");
System.out.println(a);
System.out.println(b);
dhilmathy
  • 2,800
  • 2
  • 21
  • 29
Sambath S
  • 1
  • 1

1 Answers1

1
b = a; //Remove this line

This is where the problem is. You are referencing the same object. You need to create a new object instead.

Rather than doing above, you should do,

ArrayList<JSONObject> b = new ArrayList<JSONObject>(a);

UPDATE

The above ArrayList<JSONObject> b = new ArrayList<JSONObject>(a)method will won't work as this will create a shallow copy of the list. The actual object would remain the same. For creating deep copy you will have to create a copy of each of the objects and add to a new list. Or you could use serialize/deserialize as explained here or,

You can do this if there is one layer of nested objects. here

amazing_milkha
  • 148
  • 1
  • 10