public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = 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;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Person)) {
return false;
}
Person p = (Person) obj;
return this.name.equals(p.name) && this.age == p.age;
}
}
public class HashSetDemo {
public static void main(String[] args) {
HashSet<Person> set = new HashSet<Person>();
Person p1 = new Person("陈浩南",28);
Person p2 = new Person("十三妹",23);
Person p3 = new Person("陈小春",26);
Person p4 = new Person("黄秋生",38);
Person p5 = new Person("黄秋生",38);
Person p6 = new Person("陈小春",26);
set.add(p1);
set.add(p2);
set.add(p3);
set.add(p4);
set.add(p5);
set.add(p6);
Iterator<Person> it = set.iterator();
while (it.hasNext()) {
Person p = it.next();
System.out.println(p.getName() + "***" + p.getAge());
}
}
}
我这样执行可是还是不能保证元素的唯一,为什么啊。 |