//*********************Student
import java.util.Objects;
public class Student {
public String name;
public int age;
Student(){}
Student(String name,int age){
this.name=name;
this.age=age;
}
public String toString(){//重写toString()
return "name: "+name+" age: "+age;
}
public boolean equals(Object o) {//重写equals()
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
public int hashCode() {//重写hashCode()
return Objects.hash(name)+age;
}
}
//********************StudentTest
import java.util.HashSet;
public class StudentTest {
public static void main(String[] args) {
HashSet<Student> hs=new HashSet<>();
Student s1=new Student("zs",19);//s1
Student s2=new Student("zs",19);//s2
Student s3=new Student("ls",19);//s3
hs.add(s1);//加入
集合hs.add(s2);//
hs.add(s3);//
//s1,s2,equals()返回true,s2不会加入集合
for(Student it:hs) {//遍历HasSet
System.out.println(it);
}
}
}