ArrayList 内 放入Map 时,元素重复

来源:互联网 发布:传媒杂志 知乎 编辑:程序博客网 时间:2024/06/07 22:19

向一个ArrayList 里添加元素,元素类型为Map 的时候,会出现这样的问题:如果list 内有 5个 map 元素,那么取出来的 所有 map 元素均相同,有相同的key 和 value。

     出现问题的错误代码:

                  for(int i=0;i<arr.length();++i){  

                                 temp = (JSONObject) arr.get(i);    
                                 mapTemp.clear();  
                                 mapTemp.put("materialName", temp.getString("materialName"));  
                                 mapTemp.put("materialFormat", temp.getString("unitName"));   
                                 mapTemp.put("id", temp.getString("id"));  
                                 listItem.add(mapTemp);  
                                 Log.i("mapGet=========", listItem.get(i).get("materialName"));  
                            }  

                         这样写的目的本来是想提高效率,不用每次都重新创建MAp.就使用他的clear方法。结果发现竟然List中存放的MAP数据都是相同的。当时觉得很不可理解。
                       后来经过跟踪发现了问题,List每次把map的引用存进去,当调用map的clear()方法后,map里面数据会被清空,最后map的数据就是最后放进去的。而List里放    的  都 是这个map的引用。因此也就不难理解为什么会出现存放的数据是最后一次放进去的情况了。
解决的方法就是每次都要创建。。。。

正确的方法:
                   HashMap<String, String> mapTemp = null;  
                        for(int i=0;i<arr.length();++i){  
                            temp = (JSONObject) arr.get(i);    
                           mapTemp = new HashMap<String, String>();  
                             mapTemp.put("materialName", temp.getString("materialName"));  
                             mapTemp.put("materialFormat", temp.getString("unitName"));   
                             mapTemp.put("id", temp.getString("id"));  
                             listItem.add(mapTemp);  
                             Log.i("mapGet=========", listItem.get(i).get("materialName"));  
                        }  
0 0
原创粉丝点击