JSONObject 的清除
JSONObject 的清除
原因:在循环内,亦或其它需要重复使用某json的情况下。
.clear()方法:
ArrayList<JSONObject> item = new ArrayList<JSONObject>();
JSONObject sendAuth2 = new JSONObject();
sendAuth2.put("1",1);
item.add(sendAuth2);
System.out.println(item);
sendAuth2.clear();
//sendAuth2 = null;
//sendAuth2 = new JSONObject();
sendAuth2.put("2",2);
System.out.println(sendAuth2);
System.out.println(item);
结果:
[{"1":1}]
{"2":2}
[{"2":2}]
可以看出,clear之后,引用方与清除方数据均发生变化。
不符合需求,pass。
数据存储在地址,clear清除为对地址进行改变,暂不知是将地址迁移,还是删除地址数据。所以导致引用方数据也发生了变化。
new JSONObject():
ArrayList<JSONObject> item = new ArrayList<JSONObject>();
JSONObject sendAuth2 = new JSONObject();
sendAuth2.put("1",1);
item.add(sendAuth2);
System.out.println(item);
//sendAuth2.clear();
//sendAuth2 = null;
sendAuth2 = new JSONObject();
sendAuth2.put("2",2);
System.out.println(sendAuth2);
System.out.println(item);
结果:
[{"1":1}]
{"2":2}
[{"1":1}]
与我们所需结果一致。
null:
ArrayList<JSONObject> item = new ArrayList<JSONObject>();
JSONObject sendAuth2 = new JSONObject();
sendAuth2.put("1",1);
item.add(sendAuth2);
System.out.println(item);
//sendAuth2.clear();
sendAuth2 = null;
//sendAuth2 = new JSONObject();
sendAuth2.put("2",2);
System.out.println(sendAuth2);
System.out.println(item);
结果:
[{"1":1}]
Exception in thread "main" java.lang.NullPointerException
at com.seeyon.demo.main(demo.java:24)
这个不晓得是哪位神仙说的赋值为null,引以为戒啊码友们。