java – 为什么clear hashmap方法清除数组列表中添加的map
发布时间:2020-12-15 04:47:36 所属栏目:Java 来源:网络整理
导读:我正在尝试重用相同的HashMap,例如下面的例子来填充列表.首先,我在地图中添加了一些值,将地图添加到列表中,然后清除地图,以便再次添加新值并在列表中添加第二组值,依此类推…… 但是,似乎clear()方法还删除了先前在列表中添加的值,如果我不使用clear()方法,
我正在尝试重用相同的HashMap,例如下面的例子来填充列表.首先,我在地图中添加了一些值,将地图添加到列表中,然后清除地图,以便再次添加新值并在列表中添加第二组值,依此类推……
但是,似乎clear()方法还删除了先前在列表中添加的值,如果我不使用clear()方法,则先前在列表中添加的每组值都会被新的值集覆盖,以便最终在这个特殊的例子我将在列表中有4个相同的值集. 我做错了什么? List<HashMap<String,String>>dataList = new ArrayList<HashMap<String,String>>(); HashMap<String,String> map = new HashMap<String,String>(); map.put(Answer.ID,"0"); map.put(Answer.IMAGE,"color_icon_awesome"); map.put(Answer.TITLE,firstOption); dataList.add(map); map.clear(); map.put(Answer.ID,"1"); map.put(Answer.IMAGE,secondOption); dataList.add(map); map.clear(); map.put(Answer.ID,"2"); map.put(Answer.IMAGE,thirdOption); dataList.add(map); map.clear(); map.put(Answer.ID,"3"); map.put(Answer.IMAGE,fourthOption); dataList.add(map); map.clear(); 解决方法
dataList.add(map)将在列表中放置对map的引用,因此它不是副本.然后当你执行map.clear()之后,它也会删除列表中地图的内容,因为它是完全相同的对象.改为dataList.add(map.clone())或(最好)做map = new HashMap<>();然后.
map.put(Answer.ID,"0"); map.put(Answer.IMAGE,"color_icon_awesome"); map.put(Answer.TITLE,firstOption); dataList.add(map); map = new HashMap<>(); 旁注:您的代码看起来像是可以使用对象而不是地图: class AnswerObject { private String id; private String image; private String title; public AnswerObject(String id,String image,String title) { this.id = id; this.image = image; this.title = title; } // some getters and setters and some other usefull code } 这应该使您的代码更好,更可读 List<AnswerObject> dataList = new ArrayList<>(); dataList.add(new AnswerObject("0","color_icon_awesome",firstOption)); dataList.add(new AnswerObject("1",secondOption)); dataList.add(new AnswerObject("2",thirdOption)); dataList.add(new AnswerObject("3",fourthOption)); 但随意忽略;-) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |