hashCode()与equals()必须同时复写

本文解释了hashCode()与equals()方法的重要性及如何正确地同时复写这两个方法,以避免在使用Map和Set等集合时出现问题。并通过实例演示了如果不正确复写hashCode()可能导致的内存溢出风险。

hashCode()与equals()必须同时复写,

成对出现,复写equals必须复写hashCode,否则会造成Map、Set等异常。

如通过put覆盖原map中的键值对,但如果只复写了equals,会造成map.gey(existKey)返回为null,从而map里出现多个同样的key,进一步造成内存溢出。因此,必须同时复写hashCode,使map.gey(existKey) -> value

实验如下:

static class Cluster {
    String name = null;
    int hostCnt = 0;
    String type = null;

    Cluster(String name, int hostCnt, String type) {
        this.name = name;
        this.hostCnt = hostCnt;
        this.type = type;
    }

    @Override
    public boolean equals(Object other) {
        return (other instanceof Cluster) && this.name.equals(((Cluster)other).name) && this.hostCnt == ((Cluster)other).hostCnt;
    }
    @Override
    public int hashCode() {
        return this.name.hashCode() + this.hostCnt;
    }
}

public static void main(String[] args) throws Exception {
    Cluster c1 = new Cluster("cluster1", 100, "store");
    Cluster c2 = new Cluster("cluster1", 100, "search");
    Cluster c3 = new Cluster("cluster2", 40, "store");
    Set<Cluster> clusters = new HashSet<>();
    clusters.add(c1);
    clusters.add(c2);
    clusters.add(c3);
    System.out.println(clusters.size()); // 不重载hashCode(),输出为3,重载后,输出为2
    clusters.stream().forEach(c -> System.out.println(c.name + ", " + c.hostCnt + ", " + c.type));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值