Java 如何正确重写student类的equals方法,使HashSet能够区分student类的duplicare对象
这是我的学生类,我想根据名称字段区分学生对象。但当执行主类时,我得到了错误的输出Java 如何正确重写student类的equals方法,使HashSet能够区分student类的duplicare对象,java,Java,这是我的学生类,我想根据名称字段区分学生对象。但当执行主类时,我得到了错误的输出 public class Student { int id; String name; public Student(String name, int id) { this.name=name; this.id= id; } public int hashCode() { return this.id; } public String toString() { return
public class Student {
int id;
String name;
public Student(String name, int id)
{
this.name=name;
this.id= id;
}
public int hashCode()
{
return this.id;
}
public String toString()
{
return "Student: "+this.name+"@"+Integer.toHexString(hashCode());
}
public boolean equals(Object o)
{
if(o instanceof Student)
{
String name=this.name;
Student s=(Student)o;
if(s.name.equals(name))
return true;
else
return false;
}
else
return false;
}}
//这是我的主课
public class HashSett {
public static void main (String[] args)
{
HashSet<Student> h=new HashSet<>();
h.add(new Student("Nimit",1));
h.add(new Student("Rahul",3));
h.add(new Student("Nimit",2));
System.out.println(h);
}
}
为什么要添加两次“Nimit”对象?您的
hashCode
与您的equals
实现不匹配。如果a.equals(b)
为真,a.hashCode==b.hashCode()
也必须为真
由于equals
仅要求名称相等,hashCode
应返回name.hashCode()
从Eclipse生成选项生成toString、hashCode和equals,或者从任何IDE生成类似选项,这都不是理想的,因为这不符合他的要求。
[Student: Nimit@1, Student: Nimit@2, Student: Rahul@3]
public int hashCode()
{
return name.hashCode();
}