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
    }
}
原文地址:https://www.cnblogs.com/sunzhongyu008/p/11233487.html