zoukankan      html  css  js  c++  java
  • 【HashMap:用对象作为KEY】

    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
    终身学习者
  • 相关阅读:
    《人月神话》阅读笔记3
    第十五周总结
    《人月神话》阅读笔记2
    对正在使用的输入法评价
    课堂练习(找水王问题)
    第二阶段冲刺第十天
    第二阶段冲刺第九天
    第二阶段冲刺第八天
    第二阶段冲刺第七天
    openwrt U盘启动
  • 原文地址:https://www.cnblogs.com/zuixinxian/p/10341180.html
Copyright © 2011-2022 走看看