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比較的是兩個變量的非空對象的引用。
源碼:
1
2
3
|
public boolean equals(object obj) { return ( this == obj); } |
通過源碼我們看到,原始類equals其實與“==”是等價的。
—finalize—
—getclass—
—hashcode—
inthejavaprogramminglanguage,everyclassimplicitlyorexplicitlyprovidesahashcode()method,whichdigeststhedatastoredinaninstanceoftheclassintoasinglehashvalue(a32-bitsignedinteger).thishashisusedbyothercodewhenstoringormanipulatingtheinstance–thevaluesareintendedtobeevenlydistributedforvariedinputsforuseinclustering.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())
源碼:
1
2
3
|
public string tostring() { return getclass().getname() + "@" + integer.tohexstring(hashcode()); } |
返回一個格式為類名+@+該類的hash值。
—wait—
finalize()
總結
以上就是本文關于java源碼閱讀之java.lang.object的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/lee_sire/article/details/53466444