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,引以为戒啊码友们。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值