import java.util.*;
class Student{
String id;
String name;
public Student(String id,String name) {
this.id=id;
this.name=name;
}
public String toString() {
return id+":"+name;
}
//重写hashCode()方法
public int hashCode() {
return id.hashCode() ;//返回id属性的哈希值
}
//重写equals()方法
public boolean equals(Object obj) {
if(this==obj) {
return true;//判断是否为同一个对象
}
if(!(obj instanceof Student)) {//判断对象是否为Student类型
return false;
}
Student stu=(Student)obj;
boolean b=this.id.equals(stu.id);
return b;
}
}
public class Example {
public static void main(String[]args) {
HashSet hset=new HashSet();
hset.add(new Student("1","张三"));
hset.add(new Student("2","李四"));
hset.add(new Student("2","李四"));
System.out.println(hset);
}
}
运行结果:
[1:张三, 2:李四]