Object是所有類的父類,任何類都默認繼承Object。 Object類到底實現了哪些方法?
1. clone方法
保護方法,實現對象的淺複製,只有實現了Cloneable接口才可以調用該方法,否則拋出CloneNotSupportedException異常。
2. getClass方法
final方法,獲得運行時類型。
3. toString方法
該方法用得比較多,一般子類都有覆蓋。
4. finalize方法
該方法用於釋放資源。因為無法確定該方法什麼時候被調用,很少使用。
5. equals方法
該方法是非常重要的一個方法。一般equals和==是不一樣的,但是在Object中兩者是一樣的。子類一般都要重寫這個方法。
6. hashCode方法
該方法用於哈希查找,重寫了equals方法一般都要重寫hashCode方法。這個方法在一些具有哈希功能的Collection中用到。
一般必須滿足obj1.equals(obj2)==true。可以推出obj1.hash-Code()==obj2.hashCode(),但是hashCode相等不一定就滿足equals。不過為了提高效率,應該盡量使上面兩個條件接近等價。
7. wait方法
wait方法就是使當前線程等待該對象的鎖,當前線程必須是該對象的擁有者,也就是具有該對象的鎖。 wait()方法一直等待,直到獲得鎖或者被中斷。 wait(longtimeout)設定一個超時間隔,如果在規定時間內沒有獲得鎖就返回。
調用該方法後當前線程進入睡眠狀態,直到以下事件發生。
(1)其他線程調用了該對象的notify方法。
(2)其他線程調用了該對象的notifyAll方法。
(3)其他線程調用了interrupt中斷該線程。
(4)時間間隔到了。
此時該線程就可以被調度了,如果是被中斷的話就拋出一個InterruptedException異常。
8. notify方法
該方法喚醒在該對像上等待的某個線程。
9. notifyAll方法
該方法喚醒在該對像上等待的所有線程。
―Object―
ClassObjectistherootoftheclasshierarchy.EveryclasshasObjectasasuperclass.Allobjects,includingarrays,implementthemethodsofthisclass.――FromOracle
―釋義―
Object類是java中所有對象所繼承的父類,即便是數組也繼承了該父類(可以理解為原始類,所有類的祖先,你也許會想問:詹姆斯第一個寫的類是不是Object?)。
所有類對Object類的繼承都是隱式繼承,所以無法看到。
―Object―
默認構造方法
―clone―
―equals―
Indicateswhethersomeotherobjectis"equalto"thisone.
Theequalsmethodimplementsanequivalencerelationonnon-nullobjectreferences:―FromORacle―
原始類Object的equals比較的是兩個變量的非空對象的引用。
源碼:
public boolean equals(Object obj) { return (this == obj); }通過源碼我們看到,原始類equals其實與“==”是等價的。
―finalize―
―getClass―
―hashcode―
IntheJavaprogramminglanguage,everyclassimplicitlyorexplicitlyprovidesahashCode()method,whichdigeststhedatastoredinaninstanceoftheclassintoasinglehashvalue(a32-bitsignedinteger).Thishashisusedbyothercodewhenstoringormanipulatingtheinstancethevaluesareintendedtobeevenlydistributedforvariedinputsforuseinclustering.Thispropertyisimportanttotheperformanceofhashtablesandotherdatastructuresthatstoreobjectsingroups("buckets")basedontheircomputedhashvalues.Technically,inJava,hashCode()bydefaultisanativemethod,meaning,ithasthemodifier'native',asitisimplementeddirectlyinthenativecodeintheJVM.
Source:Wikipedia
java中每個類都隱式或者顯式的實現了Object的hashcode方法。
跟谷歌和官方個人總結,作者為什麼要在原始類中存在hashcode呢?
①、類對象的存儲優化,便於查找類對象。
②、配合equals使用。
注意:很多博客表示hashcode方法返回的是該類的物理存儲地址或者是邏輯存儲地址,這個說法是錯誤的,按照官方的說法:返回的32位值只是與類對象的存儲位置有關。
―notify―
―notifyall―
―toString―
ThetoStringmethodforclassObjectreturnsastringconsistingofthenameoftheclassofwhichtheobjectisaninstance,theat-signcharacter`@',andtheunsignedhexadecimalrepresentationofthehashcodeoftheobject.Inotherwords,thismethodreturnsastringequaltothevalueof:
getClass().getName()+'@'+Integer.toHexString(hashCode())
源碼:
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }返回一個格式為類名+@+該類的hash值。
―wait―
finalize()
總結
以上就是本文關於java源碼閱讀之java.lang.Object的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!