import java.util.*;
class TestRen
{
public static void main(String[] args)
{
Person p0= new Person();
p0.id=1;
p0.name= new Name();
p0.name.firstName="jams";
p0.name.lastName="Green";
Person p1 = new Person();
p1.id=1;
p1.name = new Name();
p1.name.firstName="jams";
p1.name.lastName="Green";
Person p2 = new Person();
p2.id=1;
p2.name = new Name();
p2.name.firstName="三";
p2.name.lastName="张";
Person p3 = new Person();
p3.id=1;
p3.name = new Name();
p3.name.firstName="四";
p3.name.lastName="李";
Set set = new HashSet();
set.add(p0);//这边元素id和name为什么都能添加进去
set.add(p1);
set.add(p2);
set.add(p3);
System.out.println(set.size());
}
}
class Person
{
int id;
Name name;
public int hashCode(){
final int num = 13;
return num*id+name.hashCode();
}
public boolean equals(Object obj){
if(obj==this){//这个this是什么
return true;
}
if(obj instanceof Person){ //instanceof在jdk哪边
Person p = (Person)obj;//这边为什么要转换?
return (this.id==pp.id && this.name.equals(p.name));
}
return false;
}
} |
|