public class HashSetDemo {
/**
* @param args
*/
public static void main(String[] args) {
HashSet hs=new HashSet();
hs.add(new Person("LISI",22));
hs.add(new Person("LISI",23));
hs.add(new Person("LISI",24));
hs.add(new Person("LISI",25));
hs.add(new Person("LISI",25));
Iterator it=hs.iterator();
while(it.hasNext()){
Person p=(Person)it.next();
System.out.println(p.getName()+"--"+p.getAge());
}
}
}
class Person {
@Override
public boolean equals(Object obj) {//覆写Object 中的equals方法
if (this==obj){
return true;
}
if(!(obj instanceof Person)){
return false;
}
System.out.println(this+".......equals........."+obj);
Person p=(Person)obj;
return this.name.equals(p.name)&&this.age==p.age;
}
@Override
public int hashCode() {//覆写hashCode方法,同时可以提高效率。(只要hashCode不同,就不需再调用equals方法。)
System.out.println(this+"......hashCode()");
return name.hashCode()+age*23;
}
private String name;
private int 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 Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String toString(){
return name+":"+age;
}