Map集合的key存储自定义对象

代码奉上

package algorithm.map;

import java.util.Objects;

/**
 * @author xiaowang
 * @creat 2024/6/8 22:18
 * @Description Java Lotus
 */
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 String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", 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);
    }
}


package algorithm.map;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/**
 * @author xiaowang
 * @creat 2024/6/8 22:19
 * @Description Java Lotus
 */
public class MapDemo5 {
    public static void main(String[] args) {
        HashMap<Student,String>stringHashMap=new HashMap<>();

        stringHashMap.put(new Student("张三",23),"北京");
        stringHashMap.put(new Student("李四",24),"上海");
        stringHashMap.put(new Student("张三",23),"北京");


        Set<Student>keys=stringHashMap.keySet();
        for (Student key : keys) {
            System.out.println(key+"----"+stringHashMap.get(key));
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值