【问题标题】:copy one array list of jsonobject to another without referencing to same将 jsonobject 的一个数组列表复制到另一个而不引用相同的
【发布时间】:2020-04-17 05:17:23
【问题描述】:

我尝试如下。 我想将一个 jsonobject 的数组列表复制到另一个而不引用相同的...., 谁能解释一下我做错了什么??

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);

【问题讨论】:

  • List&lt;JSONObject&gt; b = a.stream().collect(Collectors.toList()); Java-8 一行就可以搞定。
  • 这也会影响两个列表。,
  • 嘿 Sambath,我的回答解决了问题吗?

标签: java json reference


【解决方案1】:
b = a; //Remove this line

这就是问题所在。您正在引用同一个对象。您需要创建一个新对象。

你应该做的,而不是上面做的,

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

更新

上述ArrayList&lt;JSONObject&gt; b = new ArrayList&lt;JSONObject&gt;(a)方法将不起作用,因为这将创建列表的浅表副本。实际对象将保持不变。要创建深层副本,您必须创建每个对象的副本并添加到新列表中。或者您可以按照here 的说明使用序列化/反序列化 或者,

如果有一层嵌套对象,您可以这样做。 here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 2010-10-05
    • 2017-08-20
    • 2022-01-26
    • 2018-08-11
    相关资源
    最近更新 更多