将重复键放入 HashMap 时会发生什么?

What happens when a duplicate key is put into a HashMap?(将重复键放入 HashMap 时会发生什么?)
本文介绍了将重复键放入 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:覆盖键的值

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 时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)