实现如下
package collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
class Student{
String name;
int age;
public Student(){}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return " 姓名: "+this.getName()+" ,年龄:"
+this.getAge();
}
public boolean equals(Object obj){
Student s=(Student) obj;
return this.name.equals(s.name)&&this.age==s.age;
}
public int hashCode(){
int code=this.name.hashCode()+age*7;
return code;
}
}
public class Ex5 {
public static void main(String[] args) {
HashSet list=new HashSet();
Student s1=new Student("wl",29);
Student s3=new Student("wl",25);
Student s4=new Student("wl",29);
Student s5=new Student("wl",29);
Student s2=new Student("www",28);
Student s6=new Student("www",28);
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
list.add(s6);
Iterator it=list.iterator();
while(it.hasNext()){
Object obj=it.next();
System.out.println(obj+"\t");
}
System.out.println();
}
}
output:
姓名: wl ,年龄:29
姓名: wl ,年龄:25
姓名: www ,年龄:28
核心:hashCode()和equals()的重写