我与咖啡娘的爱恨情仇

14.HashMap存储数据并遍历(自定义对象作为key)

2018-10-15  本文已影响0人  今天庹

HashMap存储数据并遍历(自定义对象作为key)

B: 定义一个学生类,学生类中有name和age两个属性,创建三个学生对象,分别对name和age赋值,然后以key为学生对象,value为学生的学号的方式存入HashMap集合,利用两种方式遍历这个Map

package com.itheima_02;

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

    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
    
}
package com.itheima_02;

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

/*
 *  使用HashMap存储数据并遍历(自定义对象作为key)
 */
public class HashMapDemo2 {
    public static void main(String[] args) {
        //创建HashMap对象
        HashMap<Student,String> hm = new HashMap<Student,String>();
        //创建key对阿星
        Student s = new Student("zhangsan",18);
        Student s2 = new Student("lisi",20);
        Student s3 = new Student("lisi",20);
        //添加映射关系
        hm.put(s, "ITCAST001");
        hm.put(s2,"ITCAST002");
        hm.put(s3, "ITCAST002");
        
        //遍历Map对象
        //方式一:获取所有的key,通过key来获取value
        Set<Student> keys = hm.keySet();
        for (Student key : keys) {
            String value = hm.get(key);
            System.out.println(key + "---" + value);
        }
        
        System.out.println("-----");
        //方式二:获取所有结婚证对象,通过结婚证对象获取key和value
        Set<Map.Entry<Student, String>> entrys = hm.entrySet();
        for (Map.Entry<Student, String> entry : entrys) {
            Student key = entry.getKey();
            String value = entry.getValue();
            
            System.out.println(key + "---" + value);
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读