想了一个小时,没结果,求大神指点
是这样的,HashMap的key值有重复,但还是被打印了,equals方法和hashCod已重写了,这是为什么呢?---------------------------------------
public class Student {
private String name;
private Integer score;
public Student(String name, Integer score) {
this.name = name;
this.score = score;
}
public String toString() {
return "Student [name=" + name + ", score=" + score + "]";
}
public Integer hasCode() {
return name.hashCode() + score.hashCode() * 31;
}
public boolean equals(Object obj) {
Student p = (Student) obj;
if (this.name == p.name && this.score == p.score) {
return true;
}
return false;
}
}
-----------------------------------------------------------------------------------------
import java.util.Set;
import java.util.HashMap;
public class TestHashMap {
public static void main(String[] args) {
HashMap<Student, Student> ha = new HashMap<Student, Student>();
ha.put(new Student("小理", 25), new Student("小理", 25));
ha.put(new Student("小刚", 21), new Student("小娟", 23));
ha.put(new Student("小理", 25), new Student("小理", 25));
ha.put(new Student("大刚", 22), new Student("小青", 24));
ha.put(new Student("小名", 21), new Student("小晓", 21));
Set<Student> s=ha.keySet();
for(Student sl : s)
{
System.out.println(sl);
}
}
}