List<Map>中赋值覆盖问题
2016-01-06 10:37
537 查看
public static void main(String[] args) { //list赋值 List list = new ArrayList(); Map map = new HashMap(); map.put("id", 1); list.add(map); Map map2 = new HashMap(); map2.put("id", 2); list.add(map2); System.out.println(list); //newList = list*2 List newList = new ArrayList(); newList.add(list.get(0)); newList.add(list.get(1)); newList.add(list.get(0)); newList.add(list.get(1)); System.out.println(newList); //改变第3个map的id值 for(int i=0;i<newList.size();i++){ if(i==2){ Map m = (Map)newList.get(2); m.put("id", 3); } } System.out.println(newList); }
虽然修改的的是newList的第三个对象,但第一个对象id值也改变。
因为list.get(2)存的是引用,而list.get(2)和list.get(0)存放的是相同引用,内存里面同一个区域,只要一个改变,其他都会改变。
<span style="color:#ff0000;">改乘这样就行了 </span><span style="background-color: rgb(204, 204, 204);">import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Dog { public static void main(String[] args) { List list = new ArrayList(); Map map = new HashMap(); map.put("id", 1); list.add(map); Map map2 = new HashMap(); map2.put("id", 2); list.add(map2); System.out.println(list); // newList = list*2 List newList = new ArrayList(); newList.add(list.get(0)); newList.add(list.get(1)); newList.add(list.get(0)); newList.add(list.get(1)); System.out.println(newList); for (int i = 0; i < newList.size(); i++) { if (i == 2) { Map m = new HashMap(); Map n = (Map) newList.get(2); m.put(n.keySet().iterator().next(), 3); newList.set(2, m); } } System.out.println(newList); } }</span>
相关文章推荐
- [置顶] IDEA/AS快捷键收集
- Android SparseArray和HashMap 性能比较<3>
- 配置/捕捉 事务
- C#Equal的使用
- 批量分离和附加数据库
- eclipse直接使用tomcat安装程序的webapp目录调试
- 10个免费的服务器监控工具
- java学习日志(1):命令行and小程序
- js获取字符串字节数方法小结
- 线程中断
- C++中变量和类的定义
- C Primer Plus3-6
- C Primer Plus3-7
- 零基础制作物理引擎--创造世界
- -128与-0
- Highchart :tooltip工具提示
- 互联网协议总结
- 数据库查数据库名,表名,列表
- 2015年十大测试工具你认识几个
- 大数据建设思路