Does adding a duplicate value to a HashSet/HashMap replace the previous value(向 HashSet/HashMap 添加重复值是否会替换先前的值)
问题描述
请考虑以下代码:
HashSet hs = new HashSet();
hs.add("hi"); -- (1)
hs.add("hi"); -- (2)
hs.size()
将给出 1,因为 HashSet
不允许重复,因此只会存储一个元素.
hs.size()
will give 1 as HashSet
doesn't allow duplicates so only one element will be stored.
我想知道如果我们添加了重复元素,那么它是替换前一个元素还是根本不添加它?
I want to know if we add the duplicate element, then does it replace the previous element or it simply doesn't add it?
另外,对于同样的情况,使用HashMap
会发生什么?
Also, what will happen usingHashMap
for the same case?
推荐答案
以HashMap
,它将旧值替换为新值.
In the case of HashMap
, it replaces the old value with the new one.
在 的情况下HashSet
,该项没有插入.
In the case of HashSet
, the item isn't inserted.
这篇关于向 HashSet/HashMap 添加重复值是否会替换先前的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:向 HashSet/HashMap 添加重复值是否会替换先前的值


基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01