package com.yjf.esupplier.common.test; import java.util.HashMap; import java.util.Set; /** * @author shusheng * @description 用对象作为KEY,重写比较方法 * @Email shusheng@yiji.com * @date 2018/12/17 17:57 */ public class MapDemo3 { public static void main(String[] args) { HashMap<Student, String> hm = new HashMap<Student, String>(); //创建学生对象 Student s1 = new Student("貂蝉", 27); Student s2 = new Student("王昭君", 28); Student s3 = new Student("西施", 29); Student s4 = new Student("杨玉环", 26); Student s5 = new Student("杨玉环", 26); //添加元素 hm.put(s1, "100"); hm.put(s2, "101"); hm.put(s3, "102"); hm.put(s4, "103"); hm.put(s5, "104"); //遍历 Set<Student> set = hm.keySet(); for (Student key : set) { String value = hm.get(key); System.out.println(key.getName() + "---" + key.getAge() + "---" + value); } } } class Student{ private String name; private int age; 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 int hashCode() { return this.name.hashCode() + this.age * 113; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Student)) { return false; } Student s = (Student) obj; return this.name.equals(s.name) && this.age == s.age; } }
执行结果:
杨玉环---26---104 貂蝉---27---100 王昭君---28---101 西施---29---102