了解Java HashSet的contains方法
关于 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果哈希码方法是基于
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 secondcontains
check will use the new hash value, and won't find the object you were looking for. This is becauseHashSet
s first search by hash code, so they won't bother callingequals
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.由于您的新
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)