重写HashMap的equals和hashCode方法

给你一囗甜甜゛ 提交于 2019-12-10 14:29:43

首先定义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<Key,String> 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!