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

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

问题描述

如果我多次将相同的键传递给 HashMapput 方法,原始值会发生什么变化?如果甚至该值重复呢?我没有找到任何相关文档.

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.

案例 1:覆盖某个键的值

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

我们得到肯定不是.

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

我们得到一个.

但是其他值会发生什么?我正在向一名学生教授基础知识,有人问我这个问题.Map 是否像一个桶,其中引用了最后一个值(但在内存中)?

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)?

推荐答案

根据定义,put 命令替换映射中与给定键关联的先前值(概念上类似于数组索引操作原始类型).

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).

地图只是删除了对值的引用.如果没有其他对象持有对该对象的引用,则该对象有资格进行垃圾回收.此外,Java 返回与给定键关联的任何先前值(如果不存在,则返回 null),因此您可以确定那里存在什么并在必要时维护一个引用.

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.

此处的更多信息:HashMap 文档

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

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