标题:想了一个小时,没结果,求大神指点
只看楼主
晚来风
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2015-8-2
结帖率:100%
已结贴  问题点数:10 回复次数:2 
想了一个小时,没结果,求大神指点
是这样的,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);
         }
        
    }
}
搜索更多相关主题的帖子: equals return public private 
2015-08-20 21:56
calix
Rank: 9Rank: 9Rank: 9
等 级:贵宾
威 望:28
帖 子:249
专家分:1442
注 册:2015-5-4
得分:10 
程序代码:
@Override//最好把这个加上,可以帮你检查继承
public int hashCode() {//方法名写错了
    return name.hashCode() + score.hashCode() * 31;
}

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

2015-08-21 09:02
晚来风
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2015-8-2
得分:0 
回复 2楼 calix
感谢
2015-08-23 01:27



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-456608-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.157098 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved