zoukankan      html  css  js  c++  java
  • Map中自定义Key

    在使用Map集合的时候可以发现对于Key和Value的类型实际上都可以由使用者定义,这就意味着可以用自定义的类来进行Key类型的设置。
    对自定义Key类型所在的类中,一定要覆写hashCode()和equals()方法。
    package com.iterator.demo;
    
    import java.util.HashMap;
    import java.util.Map;
    
    class Person{
        private String name;
        private int age;
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
        @Override
        public int hashCode() {//覆写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) {//覆写equals()
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Person other = (Person) 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;
        }
    }
    
    public class IteratorDemo {
        public static void main(String[] args) {
            Map<Person, String> map = new HashMap<Person, String>();//使用自定义类作为Key
            map.put(new Person("张三",18), "张三疯");
            map.put(new Person("李四",18), "李四光");
            map.put(new Person("王五",18), "王五哥");
            System.out.println(map.get(new Person("张三", 18)));//通过key找到value
        }
    }
  • 相关阅读:
    CentOS关闭防火墙
    CentOS 7升级Python到3.5后yum出错
    Windows本地Linux虚拟机ping不通的解决办法
    xshell上传下载文件(Windows、Linux)
    tensorflow,torch tips
    svn tips
    torch lua tips
    ios oc调用swift framework
    ios dyld: Library not loaded: @rpath/xxx.framework/xxx 之根本原因
    xcode,git tips
  • 原文地址:https://www.cnblogs.com/sunzhongyu008/p/11233487.html
Copyright © 2011-2022 走看看