今天在做微信项目时,发现了一个奇怪的问题,代码如下:
JSONObject j = new JSONObject(); List<JSONObject> list = new ArrayList<JSONObject>(); j.put("author", "1yuqiaotech"); j.put("title", "1测试标题"); //在图文消息页面点击“阅读原文”后的页面 j.put("content", "1测试asiuninasd"); j.put("digest", "1digest"); System.out.println("json1:" + j); list.add(j); j.put("author", "2yuqiaotech"); j.put("title", "2测试标题"); //图文消息页面的内容,支持HTML标签 j.put("content", "2测试asiuninasd"); j.put("digest", "2digest"); System.out.println("json1:" + j); list.add(j); System.out.println("list(0):" + list.get(0)); System.out.println("list(1):" + list.get(1));
奇怪,list中两个都是json2的内容,json1的内容不见了。
针对这个问题,做一下测试:
首先用list保存基础类型对象变量:
List<Integer> intList = new ArrayList<Integer>(); int i = 1; intList.add(i); System.out.println(intList); i = 2; intList.add(i); System.out.println(intList);
仍然用上面的JSONObject:
JSONObject j = new JSONObject(); List<JSONObject> list = new ArrayList<JSONObject>(); j.put("author", "1yuqiaotech"); j.put("title", "1测试标题"); //在图文消息页面点击“阅读原文”后的页面 j.put("content", "1测试asiuninasd"); j.put("digest", "1digest"); System.out.println("json1:" + j); list.add(j); System.out.println("list:" + list); j.put("title", "2测试标题"); System.out.println("list:" + list);打印结果:
为什么会这样呢?
这个问题要从Java存储结构来看了,对于基础类型数据,直接存储在栈中,而当像list添加new的对象时,只是将对象的引用传给放在了list中,当该引用指向的对象发生变化时,对应的list里的内容也就跟着发生变化了。
这种情况下就必须用两个不同的JSONObject对象来分别存储了。
也是我粗心大意了啊。
原文地址:http://blog.csdn.net/bruce_6/article/details/38846153