问题描述
如果我将同一个键多次传递给 HashMap
的 put
方法,原始值会怎样?如果连值都重复了怎么办?我没有找到任何关于此的文档.
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:覆盖键的值
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 时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!