• 【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
    终身学习者
  • 相关阅读:
    React同构直出优化总结
    Kubenertes资源分配之Request和Limit解析
    Node Server零基础——开发环境文件自动重载
    Vue组件开发实践之scopedSlot的传递
    【干货合集】Docker快速入门与进阶
    ES6 中的 Set
    十个书写Node.js REST API的最佳实践(上)
    oozie配置安装与原理
    Livy原理详解
    阿里(蚂蚁金服)招聘
  • 原文地址:https://www.cnblogs.com/zuixinxian/p/10341180.html
Copyright © 2020-2023  润新知