将重复密钥放入HashMap时会发生什么? [英] What happens when a duplicate key is put into a HashMap?

查看:127
本文介绍了将重复密钥放入HashMap时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我多次将相同的密钥传递给 HashMap put 方法,原始值会发生什么变化?而且,如果价值重复呢?我没有找到任何文件。



案例1:为一个关键字重写值

  Map mymap = new HashMap(); 
mymap.put(1,one);
mymap.put(1,not one);
mymap.put(1,肯定不是一个);
System.out.println(mymap.get(1));

我们得到肯定不是一个案例2:重复值

  Map mymap = new HashMap(); 
mymap.put(1,one);
mymap.put(1,not one);
mymap.put(1,肯定不是一个);
//添加了以下行:
mymap.put(1,one);
System.out.println(mymap.get(1));

我们得到一个



但其他值会发生什么?我正在向一名学生教授基础知识,并被问到这一点。 Map 就像引用最后一个值的桶(但在内存中)?

解决方案<根据定义, put 命令会替换映射中给定键的前一个值(概念上类似于原始类型的数组索引操作)。



地图只是将其参考值降到该值。如果没有其他东西持有对该对象的引用,那么该对象就有资格进行垃圾回收。此外,Java返回与给定键相关的任何以前的值(或者如果不存在,则返回 null ),因此您可以确定那里是什么并在必要时保留引用。



更多信息在这里: HashMap Doc


If I pass the same key multiple times to HashMap’s put method, what happens to the original value? And what if even the value repeats? I didn’t find any documentation on this.

Case 1: Overwritten values for a key

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"));

We get surely not one.

Case 2: Duplicate value

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"));

We get one.

But what happens to the other values? I was teaching basics to a student and I was asked this. Is the Map like a bucket where the last value is referenced (but in memory)?

解决方案

By definition, the put command replaces the previous value associated with the given key in the map (conceptually like an array indexing operation for primitive types).

The map simply drops its reference to the value. If nothing else holds a reference to the object, that object becomes eligible for garbage collection. Additionally, Java returns any previous value associated with the given key (or null if none present), so you can determine what was there and maintain a reference if necessary.

More information here: HashMap Doc

这篇关于将重复密钥放入HashMap时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆