了解Java HashSet的contains方法

发布于 2024-11-29 05:28:49 字数 359 浏览 3 评论 0原文

关于 java HashSet 的新手问题

Set<User> s = new HashSet<User>();
User u = new User();
u.setName("name1");
s.add(u);
u.setName("name3");
System.out.println(s.contains(u));

有人可以解释为什么这段代码输出 false 吗?而且这段代码甚至没有调用 User 的 equals 方法。但根据HashSet和HashMap的来源,它必须调用它。 User 的方法 equals 只是对用户名调用 equals。方法 hashCode 返回用户名的 hashCode

Newbie question about java HashSet

Set<User> s = new HashSet<User>();
User u = new User();
u.setName("name1");
s.add(u);
u.setName("name3");
System.out.println(s.contains(u));

Can someone explain why this code output false ? Moreover this code does not even call equals method of User. But according to the sources of HashSet and HashMap it have to call it. Method equals of User simply calls equals on user's name. Method hashCode return hashCode of user's name

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

少钕鈤記 2024-12-06 05:28:49

如果哈希码方法是基于name字段,然后在添加对象后更改它,那么第二次contains检查将使用新的哈希值,并获胜找不到您要找的对象。这是因为 HashSet 首先通过哈希码进行搜索,因此如果搜索失败,它们不会调用 equals

唯一可行的方法是,如果您没有覆盖equals(因此使用了默认的引用相等)并且您很幸运并且两个对象的哈希码相等。但这是一种确实不太可能发生的情况,您不应该依赖它。

一般来说,在将对象添加到 HashSet 后,您不应该更新该对象,如果该更改也会更改其哈希码。

If the hash code method is based on the name field, and you then change it after adding the object, then the second contains check will use the new hash value, and won't find the object you were looking for. This is because HashSets first search by hash code, so they won't bother calling equals if that search fails.

The only way this would work is if you hadn't overridden equals (and so the default reference equality was used) and you got lucky and the hash codes of the two objects were equal. But this is a really unlikely scenario, and you shouldn't rely on it.

In general, you should never update an object after you have added it to a HashSet if that change will also change its hashcode.

暗藏城府 2024-12-06 05:28:49

由于您的新 User 具有不同的哈希码,因此 HashSet 知道它不相等。

哈希集根据哈希码存储其项目。
HashSet 仅在找到具有相同哈希码的项时才会调用 equals,以确保这两个项实际上相等(而不是哈希冲突)

Since your new User has a different hashcode, the HashSet knows that it isn't equal.

HashSets store their items according to their hashcodes.
The HashSet will only call equals if it finds an item with the same hashcode, to make sure that the two items are actually equal (as opposed to a hash collision)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文