注册 登录
编程论坛 JAVA论坛

想了一个小时,没结果,求大神指点

晚来风 发布于 2015-08-20 21:56, 520 次点击
是这样的,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);
         }
        
    }
}
2 回复
#2
calix2015-08-21 09:02
程序代码:
@Override//最好把这个加上,可以帮你检查继承
public int hashCode() {//方法名写错了
    return name.hashCode() + score.hashCode() * 31;
}

//话说论坛这两天老进不去,不知道怎么回事

#3
晚来风2015-08-23 01:27
回复 2楼 calix
感谢
1