【java学习】object中的equals方法

本文深入探讨了Java中Object类的equals方法,详细阐述其性质:自反性、对称性、传递性和一致性。讲解了equals比较的是对象引用而非内容,并指出当重写equals时,通常需同时重写hashCode方法以保持一致性。通过实例展示了String类如何重写equals,使得内容相同返回true。此外,还强调了正确重写equals和hashCode对于集合框架的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在java.lang.Object类中可以看到对equals方法的说明
/**
* Indicates whether some other object is “equal to” this one.
*


* The {@code equals} method implements an equivalence relation
* on non-null object references:
*


  • *
  • It is reflexive: for any non-null reference value
    * {@code x}, {@code x.equals(x)} should return
    * {@code true}.
    *
  • It is symmetric: for any non-null reference values
    * {@code x} and {@code y}, {@code x.equals(y)}
    * should return {@code true} if and only if
    * {@code y.equals(x)} returns {@code true}.
    *
  • It is transitive: for any non-null reference values
    * {@code x}, {@code y}, and {@code z}, if
    * {@code x.equals(y)} returns {@code true} and
    * {@code y.equals(z)} returns {@code true}, then
    * {@code x.equals(z)} should return {@code true}.
    *
  • It is consistent: for any non-null reference values
    * {@code x} and {@code y}, multiple invocations of
    * {@code x.equals(y)} consistently return {@code true}
    * or consistently return {@code false}, provided no
    * information used in {@code equals} comparisons on the
    * objects is modified.
    *
  • For any non-null reference value {@code x},
    * {@code x.equals(null)} should return {@code false}.
    *

*


* The {@code equals} method for class {@code Object} implements
* the most discriminating possible equivalence relation on objects;
* that is, for any non-null reference values {@code x} and
* {@code y}, this method returns {@code true} if and only
* if {@code x} and {@code y} refer to the same object
* ({@code x == y} has the value {@code true}).
*


* Note that it is generally necessary to override the {@code hashCode}
* method whenever this method is overridden, so as to maintain the
* general contract for the {@code hashCode} method, which states
* that equal objects must have equal hash codes.
*
* @param obj the reference object with which to compare.
* @return {@code true} if this object is the same as the obj
* argument; {@code false} otherwise.
* @see #hashCode()
* @see java.util.HashMap
*/
如果英文不行,就看中文jdk文档:
在这里插入图片描述
总结一下:
①性质:自反 对称 传递 一致 (也就是离散数学那些东西)
②euqals比较的是地址(引用),因此true的条件比==更加严格
③重写时要重写hashCode方法

实际操作一波:
在这里插入图片描述
e1和e2的地址不同,所以false,s1和s2的内容相同但是地址不同,本来按照Object的equals方法应当输出false,但是String类重写了equals方法,当内容相同时会输出true。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民真快落

我琢磨着也没人给我打赏呀。。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值