Set<Person> list = new HashSet<Person>();
Person p1 = new Person ("s1",1);
Person p2 = new Person ("s1",2);
Person p3 = new Person ("s1",3);
Person p4 = new Person ("s1",4);
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
System.out.println(list.size());//打印出是4,為什麼啊??
}
-----------
public Person(String name, int age) {
this.age = age;
this.name = name;
}
public boolean equals(Object o) {
if(o == null)
{
return false;
}
if (o == this)
{
return true;
}
if (getClass() != o.getClass())
{
return false;
}
return this.equals(((Person) o).getName());
}
@Override
public int hashCode() {
return 1;
}
hashCode相同,並不意味著equal相等
return this.equals(((Person) o).getName());
要判斷名字
return this.getName().equals(((Person) o).getName());