问题描述
我执行了下面的代码,发现输出是 false.
i executed below code and found the output was false.
import java.util.set; import java.util.hashset; public class name { private string first, last; public name(string first, string last) { this.first = first; this.last = last; } public boolean equals(object o) { if (!(o instanceof name)) return false; name n = (name) o; return n.first.equals(first) && n.last.equals(last); } public static void main(string[] args) { sets = new hashset (); s.add(new name("donald", "duck")); system.out.println(s.contains(new name("donald", "duck"))); } }
我想知道它的行为方式以及为什么输出为 false.
i want to know how it behaves and why output is false.
推荐答案
您还需要重写 hashcode() 方法以及 equals().这两种方法都用于 hashset 的正确功能,因此如果您将 class 作为key,否则 object 类的 hashcode() 正在被使用,没有两个不同的 objects 可以被视为相同因为它们的 hashcode() 总是不同的,并且在 contains() 的情况下肯定会返回 false.
you need to override hashcode() method also along with equals(). both the methods are used for proper functionality of hashset, so must be overriden in a user-defined class if you are making that class as a key, else hashcode() of object class is getting used and no two different objects can be considered as same as their hashcode() would always be different, and will for sure return falsealways in the case of contains().