案例:HashMap集合存储学生对象并遍历

案例:HashMap集合存储学生对象并遍历

  • 需求:创建一个HashMap集合,键是学生对象,值是居住地,存储对个键值对元素,并遍历,要求保证键的唯一性,如果学生对象的成员变量值相同,我们就认为同一对象

  • 思路:

  1. 定义学生类
  2. 创建HashMap集合
  3. 创建学生对象
  4. 把学生对象添加到集合中
  5. 遍历集合:
    方式1:键找值
    方式2:键值对对象找键和值
  6. 在学生类中重写方法
    hashCode()
    equals()
  • 注意:hashMap底层结构是哈希值,重写相应的方法可以保键的唯一性(注意是键的唯一性)

以代码的内容形式展开

Student类(注意有重写方法)

package Demo;

import java.util.Objects;

public class Student {
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age && Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}


Demo类

package Demo;

import java.util.*;

public class Demo {
    public static void main(String[] args) {
        //创建HashMap()
        HashMap<Student, String> s = new HashMap<>();

        //建立集合
        Student s1 = new Student("沸羊羊",21);
        Student s2 = new Student("喜羊羊",23);
        Student s3 = new Student("懒洋洋",19);
        Student s4 = new Student("美羊羊",27);
        Student s5 = new Student("美羊羊",27);

        //添加元素
        s.put(s1,"西安");
        s.put(s2,"汉中");
        s.put(s3,"榆林");
        s.put(s4,"咸阳");
        s.put(s5,"咸阳");

        //遍历集合
        //1    根据键所找值
        Set<Student> students = s.keySet();
        for (Student x:students) {
            String sss = s.get(x);
            System.out.println(x.getName()+","+x.getAge()+","+sss);
        }

        System.out.println("================");
        //2    根据键对所找值
        Set<Map.Entry<Student, String>> entries = s.entrySet();
        for (Map.Entry<Student, String> x:entries) {
            Student key = x.getKey();
            String value = x.getValue();
            System.out.println(key.getName()+ key.getAge()+","+value);
        }


    }
}

输出的内容
喜羊羊,23,汉中
沸羊羊,21,西安
美羊羊,27,咸阳
懒洋洋,19,榆林

================

喜羊羊23,汉中
沸羊羊21,西安
美羊羊27,咸阳
懒洋洋19,榆林

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

发热的嘤嘤怪(2003计科胜胜同学)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值