首页 > 其他 > 详细

JDK Obejct “equals” 方法详解

时间:2020-04-12 12:06:51      阅读:75      评论:0      收藏:0      [点我收藏+]
public boolean equals?(Object obj)
Indicates whether some other object is "equal to" this one.
表明是否一个对象等于另一个对象(对象相等)。
注:当类具有自己的“逻辑相等”概念,且父类没有覆盖equals方法时,需要自己覆写这个方法。但是覆写该方法很容易导致错误,请慎重!
考虑到你如果需要覆写equals,需要考虑的情况远比你以为的要多,那么就尽量不去覆写它!特别是在下面几种情况下:
  • 类的每一个实例本质上是唯一的。
  • 类没必要提供“逻辑相等”的测试功能。
  • 超类已经覆盖的equals方法,且适用于你。
  • 类是私有的,或者是包级私有的,可以确定它的equals方法永远不会被调用。

覆盖equals方法需要遵守的Object规范如下:

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value xx.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and yx.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values xy, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • 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 objects is modified.
  • For any non-null reference value xx.equals(null) should return false.

 

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

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

JDK Obejct “equals” 方法详解

原文:https://www.cnblogs.com/xushibo/p/12684056.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!