目的:(考察知识点:如何在HashSet集合中添加自定义对象)
import java.util.HashSet;
class Student{
private String name;
private int age;
public Student(String name,int age){
this.age=age;
this.name=name;
}
public String toString(){
return "name:"+name+" age:"+age;
}
public int hashcode(){
return name.hashCode();
}
public boolean equals(Object obj){
Student stu=(Student) obj;
boolean b=this.name.equals(stu.name);
return b;
}
}
public class hashmap3 {
public static void main(String[] args) {
HashSet hs=new HashSet();
Student s1=new Student("大美女",11);
Student s2=new Student("小美女",12);
Student s3=new Student("小美女",12);
hs.add(s1);
hs.add(s2);
hs.add(s3);
System.out.println(hs);
}
}