Java HashMap遍历方式

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_45526489/article/details/100849610
package src.com.itheima;


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 instanceof Student)) 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 src.com.itheima;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
//练习一:俩种遍历方式
//HashMap<String,Student>
//键:Stirng 学号
//值:Student 学生对象

public class HashMapTest {
    public static void main(String[] args) {
        HashMap<String, Student> hm = new HashMap<String,Student>();
        Student s1 = new Student("林青霞",30);
        Student s2 = new Student("张曼玉",36);
        Student s3 = new Student("王祖贤",35);
        hm.put("it001",s1);
        hm.put("it002",s2);
        hm.put("it003",s3);

        //遍历
        //根据键找值
        Set<String> set = hm.keySet();
        for(String key:set){
            Student value = hm.get(key);
            System.out.println(key + "---" + value.getName()+"---"+value.getAge());

        }
        System.out.println("-----------------");
        //根据键值对对象找键和值
        Set<Map.Entry<String, Student>> set2 = hm.entrySet();
        for (Map.Entry<String, Student> me:set2) {
            String key = me.getKey();
            Student value = me.getValue();
            System.out.println(key +"---" + value.getName() + "---" + value.getAge());
        }

    }
}

在这里插入代码片

猜你喜欢

转载自blog.csdn.net/weixin_45526489/article/details/100849610