| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 520 人关注过本帖
标题:想了一个小时,没结果,求大神指点
只看楼主 加入收藏
晚来风
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
快速回复:想了一个小时,没结果,求大神指点
数据加载中...
 
   



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

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