将重复的密钥放入HashMap后会发生什么?

如果我多次将相同的键传递给HashMap的put方法,那么原始值会怎样?如果值重复出现该怎么办?我没有找到任何文档。


情况1:密钥的覆盖值


Map mymap = new HashMap();

mymap.put("1","one");

mymap.put("1","not one");

mymap.put("1","surely not one");

System.out.println(mymap.get("1"));

我们得到surely not one。


情况2:重复值


Map mymap = new HashMap();

mymap.put("1","one");

mymap.put("1","not one");

mymap.put("1","surely not one");

// The following line was added:

mymap.put("1","one");

System.out.println(mymap.get("1"));

我们得到one。


但是其他值怎么办?我在向学生教授基础知识,有人问我这个问题。是Map等,其中最后一个值引用(但在内存中)水桶?


慕勒3428872
浏览 248回答 3
3回答

明月笑刀无情

密钥的先前值将被删除,并用新的替代。如果您想保留所有值,则可以考虑实现如下所示:import org.apache.commons.collections.MultiHashMap;import java.util.Set;import java.util.Map;import java.util.Iterator;import java.util.List;public class MultiMapExample {&nbsp; &nbsp;public static void main(String[] args) {&nbsp; &nbsp; &nbsp; MultiHashMap mp=new MultiHashMap();&nbsp; &nbsp; &nbsp; mp.put("a", 10);&nbsp; &nbsp; &nbsp; mp.put("a", 11);&nbsp; &nbsp; &nbsp; mp.put("a", 12);&nbsp; &nbsp; &nbsp; mp.put("b", 13);&nbsp; &nbsp; &nbsp; mp.put("c", 14);&nbsp; &nbsp; &nbsp; mp.put("e", 15);&nbsp; &nbsp; &nbsp; List list = null;&nbsp; &nbsp; &nbsp; Set set = mp.entrySet();&nbsp; &nbsp; &nbsp; Iterator i = set.iterator();&nbsp; &nbsp; &nbsp; while(i.hasNext()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Map.Entry me = (Map.Entry)i.next();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;list=(List)mp.get(me.getKey());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for(int j=0;j<list.size();j++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(me.getKey()+": value :"+list.get(j));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java