JAVA-重写equalse规范、技巧
生活随笔
收集整理的這篇文章主要介紹了
JAVA-重写equalse规范、技巧
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
JAVA-重寫equalse規(guī)范、技巧
1、自反性
任何非空引用x,x.equalse(x) 應(yīng)該返回true2、對(duì)稱性
任何引用x和y,當(dāng)x.equals(y)返回true,y.equals(x)也應(yīng)返回true3、傳遞性
任何引用x、y和z,當(dāng)x.equalse(y)和y.equalse(z),那么x.equalse(z)也應(yīng)返回true4、一致性
如果x和y引用的對(duì)象沒(méi)有發(fā)生任何變化,那么反復(fù)x.equals(y)都應(yīng)返回一樣的結(jié)果5、任何非空引用 x.euqals(null) 都應(yīng)返回 false
6、重寫equalse時(shí),也要重寫hashCode方法
equalse和hashCode定義必須一致,當(dāng)x.equalse(y) 為true,那么x.hashCode()必須等于y.hashCode();例
import java.util.Objects;public class Parent { }class SubObject extends Parent {private String name;@Overridepublic boolean equals(Object otherObject) {//檢測(cè)this和otherObject是否是同一個(gè)對(duì)象if (this == otherObject) return true;//null一律返回 falseif (otherObject == null) return false;//是否是同一類型,擇一if (getClass() != otherObject.getClass()) return false;//1、當(dāng)需要判斷具體類型時(shí)if (!(otherObject instanceof Parent)) return false;//2、本類及其子類均可//將otherObject轉(zhuǎn)換相應(yīng)對(duì)象SubObject other = (SubObject) otherObject;//比較域,根據(jù)業(yè)務(wù)需求Objects.equals(this.name, other.name);return true;}@Overridepublic int hashCode() {//如果equalse方法比較的是name,那么hashCode方法就要散列namereturn Objects.hash(name);} }總結(jié)
以上是生活随笔為你收集整理的JAVA-重写equalse规范、技巧的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: springBoot整合redis使用介
- 下一篇: React开发(154):注意div得写