HashMap存储自定义类型键值

HashMap存储自定义类型键值

键值key为:(学号,姓名.年龄) value为居住地址
我们需要创建Student类
在类中定义id name age

package demo01.demo11.Map;

import java.util.Objects;

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

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", 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 id == student.id &&
                age == student.age &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {

        return Objects.hash(id, name, age);
    }

    public int getId() {

        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    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;
    }

    public Student(int id, String name, int age) {

        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Student() {

    }
}

在主函数中 首先定义一个HashMap的集合<K,V> .K为Student类 ,V为String类
使用put方法将<K,V>存储到map集合中.,获取 所有的 entry对象 entrySet
遍历得到每一个entry对象.用getKey()与getValue()获取他们的键和值.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class DemotestHashMap {
    public static void main(String[] args) {
        Map<Student,String>map=new HashMap<Student,String>();
        map.put(new Student(177555,"徐某",22),"北京");
        map.put(new Student(177444,"胡歌",38),"上海");
        map.put(new Student(177666,"曹操",55),"魏国");
        map.put(new Student(177777,"刘备",45),"蜀国");
        map.put(new Student(177888,"孙权",39),"吴国");
        Set<Map.Entry<Student,String>> entrySet=map.entrySet();
        for (Map.Entry<Student,String> entry :entrySet
             ) {
            Student key=entry.getKey();
            //如果不重写toString方法,会输出地址值
            String value=entry.getValue();
            System.out.println(key+"居住地是:"+value);
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值