将重复值添加到HashSet / HashMap将替换以前的值 [英] Does adding a duplicate value to a HashSet/HashMap replace the previous value

查看:683
本文介绍了将重复值添加到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将替换以前的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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