今天在做微信项目时,发现了一个奇怪的问题,代码如下:
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));
这段代码的目的是将两个JSON格式的内容放在list里,首先new一个JSONObject对象,将第一个内容put到里面,然后将这个JSONObject添加到list中;接着为这个JSONObject重新put值,那么之前的值将会被覆盖掉,新的内容就会被put到该JSONObject中,然后将这个JSONObject添加到list中;想象中此时list里应该有两个不同的JSON对象了,打印结果:
奇怪,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对象来分别存储了。
也是我粗心大意了啊。
您的关注是我坚持写作的动力,如果觉得有用,欢迎关注我的微信,海量学习资源免费送!