class SetDemo
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
HashSet s=new HashSet();
s.add(new Person("jine",12));
s.add("asdad");
for(Iterator it=s.iterator();it.hasNext();){
Object obj=it.next();
if(obj instanceof Person){
Person p=(Person)obj;
sop(p.getName()+"....."+p.getAge());
}
}
}
}
class Person
{
private String name;
private int age;
Person(String name,int age){
this.name=name;
this.age=age;
}
public String getName()
{
return name;
}
public int getAge(){
return age;
}
public int hashCode(){
sop("hashcode:"+12);
return 12;
}
public boolean equals(Object obj){
if(!(obj instanceof Person))//一定要判断
{
sop("diaoyongzhe:"+name);
throw new RuntimeException("shuju leixing budui ");
}
Person p=(Person)obj;
sop(p.getName().equals(this.name)&&age==p.getAge());
return p.getName().equals(this.name)&&age==p.getAge();
}
void sop(Object obj)
{
System.out.println(obj);
}
}
|
|