HashMap集合练习之键是Student值是String

public class MapDemo {
    public static void main(String[] args) {
        //创建HashMap集合对象
        HashMap<Student,String> hm = new HashMap<Student, String>();

        //创建学生对象
        Student s1 = new Student("aabb",20);
        Student s2 = new Student("赤瞳", 21);
        Student s3 = new Student("dmh", 33);
        Student s4 = new Student("aabb",20);

        //把学生添加到集合
        hm.put(s1,"东营");
        hm.put(s2,"bzd");
        hm.put(s3,"dytv");
        hm.put(s4,"北京");

        //遍历集合
        Set<Student> keySet = hm.keySet();
        for (Student key : keySet){
            String value = hm.get(key);
            System.out.println(key.getName()+","+key.getAge()+","+value);
        }
    }
}

 

在未重写equals()方法和hashCode()情况下的代码运行结果:

未能保证元素的唯一性

 

 

重写equals()方法和hashCode()情况下的代码运行结果:

 

 保证了元素的唯一性

posted @ 2020-04-10 16:43  硬盘红了  阅读(247)  评论(0编辑  收藏  举报