本文介绍了理解包含Java HashSet的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于java HashSet的新手问题

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));

有人可以解释为什么这段代码输出错误?此外,此代码甚至不调用User的equals方法。但根据HashSet和HashMap的来源,它必须调用它。方法等于用户只需在用户名上调用equals。方法hashCode返回用户名的hashCode

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

推荐答案

如果哈希码方法基于名称字段,然后你在添加对象后更改它,然后第二个包含检查将使用新的哈希值,并且找不到你的对象正在寻找。这是因为 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.

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

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

这篇关于理解包含Java HashSet的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 15:27