import java.util.*;
class Person
{
private String name;
private int age;
Person(String name,int age){
this.name=name;
this.age=age;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
public int hashCode(){
System.out.println(this.name+".....hashCode");
return this.hashCode()+this.age*7;
}
public boolean equals(Object obj){
if(!(obj instanceof Person))
return false;
Person p=(Person)obj;
System.out.println(this.name+"...equals"+p.name);
return this.name.equals(p.name)&&this.age==p.age;
}
}
class HashSetDemo
{
public static void sop(Object obj){
System.out.println(obj);
}
public static void main(String[] args)
{
HashSet hs=new HashSet();
Iterator it=hs.iterator();
hs.add(new Person("張三",18));
hs.add(new Person("李四",17));
hs.add(new Person("張三",18));
hs.add(new Person("王五",19));
sop(hs.contains(new Person("張三",18)));
sop(hs.remove(new Person("張三",18)));
while(it.hasNext()){
Person p=(Person)it.next();
System.out.println(p.getName()+"---"+p.getAge());
}
}
}
請查看自己的Person class中的hashCode方法,方法中又調用了this的hashCode,反復遞歸調用。所以會死循環。