閱讀jdk API我們知道Object class在java.lang包下。Object class是Object結構的跟。
jdk1.8 API在線地址 :https://blog.fondme.cn/apidoc/jdk-1.8-baidu/
Object class中的方法有
hashCode(),equals(),clone(),notify(),notifyAll(),wait(),finalize()
package java.lang; public class Object { private static native void registerNatives(); static { registerNatives(); } public final native Class<?> getClass(); public native int hashCode(); public boolean equals(Object obj) { return (this == obj); } protected native Object clone() throws CloneNotSupportedException; public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } public final native void notify(); public final native void notifyAll(); public final native void wait(long timeout) throws InterruptedException; public final void wait(long timeout, int nanos) throws InterruptedException { if (timeout < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (nanos < 0 || nanos > 999999) { throw new IllegalArgumentException( "nanosecond timeout value out of range"); } if (nanos > 0) { timeout++; } wait(timeout); } public final void wait() throws InterruptedException { wait(0); } protected void finalize() throws Throwable { } }
1.首先看equals()方法。
public boolean equals(Object obj) { return (this == obj); }
equals方法是用來比較其他對象是否等於此對象。
equals方法在非空對象引用上實現等價關系:
自反性:對於任何的非空的參考值x, x.equals(x) 應該返回true。
對稱性:對於任何非空引用值x和y,x.equals(y)應該返回true,當且僅當y.equals(x)返回true。
傳遞性:對於任何非空引用值x,y,z 。x.equlas(y)返回true,y.equals (z)返回true。然后x.equals(z)應該返回true。
一致性:對於任何非空引用值x,y。多次調用x.equals (y) 始終返回true或false。在不修改x和y 的值的情況下一直成立。
對於任何非空參考值x,x.equals(null) 始終返回false。
該equals
類方法Object
實現對象上差別可能性最大的相等關系; 也就是說,對於任何非空的參考值x
和y
,當且僅當x
和y
引用相同的對象( x == y
具有值true
)時,該方法返回true
。
請注意,無論何時覆蓋該方法,通常需要覆蓋hashCode
方法,以便維護hashCode
方法的通用合同,該方法規定相等的對象必須具有相等的哈希碼。
2. equals方法比較字符串是否相等時。
private final char value[];
public boolean equals(Object anObject) { if (this == anObject) { return true; }
//判斷是否是String類型的實例 if (anObject instanceof String) { String anotherString = (String)anObject; //強轉為String類型 int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }
3.equals判斷對象是否相等時;
重寫equals和hashCode方法
@Override public boolean equals(Object o) { if (this == o) return true; //判斷內存地址是否相同 相同返回true if (!(o instanceof UserInfo)) return false;//判斷被比較的對象與此對象是否是同一類型的,不同類型返回false UserInfo userInfo = (UserInfo) o;//強制類型轉換 將被比較類型轉換為此類型 //分別比較兩對象的屬性值時候相同 只要存在一個屬性值不相同返回false 全部相同返回true if (!getUserid().equals(userInfo.getUserid())) return false; if (!getUname().equals(userInfo.getUname())) return false; return getUage().equals(userInfo.getUage()); } @Override public int hashCode() { int result = getUserid().hashCode(); result = 31 * result + getUname().hashCode(); result = 31 * result + getUage().hashCode(); return result; }