重写HashMap的equals和hashCode方法

首先定义HashMap的key,这个类中重写equals和hashcode方法:

public class Key {
    String key;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public Key(String key) {
        this.key = key;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Key key1 = (Key) o;
        return Objects.equals(key, key1.key);
    }

    @Override
    public int hashCode() {

        return key.hashCode();
    }
}

然后创建使用:

        HashMap map=new HashMap();
        Key key=new Key("hyb");
        map.put(key,key.getKey());
        Key key2=new Key("hyb");
        System.out.println(map.get(key2));

执行输出:

hyb

Process finished with exit code 0

总结:因为重写了equals和hashCode方法,在从map中获取key2时会发现存在map的key也是hyb,从而输出值为hyb

你可能感兴趣的:(笔记)