【Java】为什么equals()和hashCode()需要同时重写?

本文探讨了Java中equals()和hashCode()方法的重要性。equals()遵循自反性、对称性、传递性、一致性和非空性的规范,而hashCode()则需保证在对象未变时返回相同hash值。当重写equals()时,必须一同重写hashCode(),以确保与基于hash的集合如HashMap、HashSet和Hashtable的兼容性。同时,解释了为何选择31作为乘子的原因。
摘要由CSDN通过智能技术生成

equals()

首先看下Object中的equals(),仅简单的用==比较两个对象

public boolean equals(Object obj) {
    return (this == obj);
}

源码中对equals()的注释如下

Indicates(指出) whether some other object is "equal to" this one.

The equals method implements an equivalence(等价) relation on non-null
object references:

    1. It is reflexive(自反的): for any non-null reference value
    x, x.equals(x) should return true.

    2. It is symmetric(对称的): for any non-null reference values
    x and y, x.equals(y) should return true if and only if

    3. It is transitive(传递的): for any non-null reference values
    x, y, and z, if x.equals(y) returns true and y.equals(z) returns
    true, then x.equals(z) should return true.

    4. It is consistent(一致的): for any non-null reference values x and
    y, multiple invocations of x.equals(y) consistently(始终) return true
    or consistently return false, provided no information used in equals
    comparisons on the
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值