我重写的equals方法,但为什么运行结果还有重复的?
package Test_05;
import java.util.HashSet;
import java.util.Iterator;
class Person{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 重写hashCode方法,返回name属性的哈希值
public int hashCode(){
return name.hashCode();
}
// 重写equals方法
public boolean equals(Object obj){
if(this.name == obj)
return true;
return false;
}
public String toString(){
return "Person " + name + age;
}
}
public class T5_10 {
public static void main(String[] args) {
// 创建HashSet对象
HashSet hs = new HashSet();
// 将Person对象存入集合
hs.add(new Person("lisa", 21));
hs.add(new Person("lisi", 32));
hs.add(new Person("lisi", 32));
hs.add(new Person("leilei", 31));
hs.add(new Person("lusi", 25));
hs.add(new Person("lusi", 25));
// 遍历集合中的元素
Iterator it = hs.iterator();
while (it.hasNext()) {
Person p = (Person) it.next();
System.out.println(p);
}
}
}