標籤:
Object有9個方法需要瞭解;
分別是如下的:
1)public final native Class<?> getClass();
2)public native int hashCode();
3)public boolean equals(Object obj) {return (this == obj);}
4)protected native Object clone() throws CloneNotSupportedException;
5)public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
6)public final native void notify();
7)public final native void notifyAll();
8)protected void finalize() throws Throwable { }
9)public final native void wait(long timeout) throws InterruptedException;
// wait方法重載有三個,但是真正意義上只有一個有用,有用這個也都是內部實現native
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 >= 500000 || (nanos != 0 && timeout == 0)) { timeout++; } wait(timeout); }
Object 9個方法的具體介紹;
1、public final native Class<?> getClass();
擷取對象的類全稱,也就是:class package.class
2、public native int hashCode();
返回的是當前對象的記憶體位址。無論何時,對同一個對象調用hashCode()都應該產生同樣的值,不管這個對象是否發生過內部改變。
3、public boolean equals(Object obj) {return (this == obj);}
通過記憶體位址判斷對象是否相等。
4、protected native Object clone() throws CloneNotSupportedException;
對象複製,這個是深度複製時的必須實現的方法,同時一般都會調用object的clone方法;
5、public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
返回類名[email protected]+地址的16進位數
6、public final native void notify();
線程喚醒
7、 public final native void notifyAll();
線程喚醒
8、protected void finalize() throws Throwable { }
記憶體回收行程要回收對象的時候,首先要調用這個類的finalize方法,一般的純Java編寫的Class不需要重新覆蓋這個方法,因為Object已經實現了一個預設的,除非我們要實現特殊的功能。
9、public final native void wait(long timeout) throws InterruptedException;
線程阻塞,等待一定時間
10、關於equals與hashCode
一般只要重寫二者之一,你們另一個也有必要要重寫,但是不是強求的。原因是equals方法使用的是記憶體位址比較,同樣hashCode返回的也是記憶體位址,那麼如果採用equals相等,然而hashCode相等的確是說不通的,應該是equals為true,那麼hashCode的值一定相同;反之不成立。另外,使用方面一個很大的因素就是Map的key,因為我們知道Map的key代碼:
public V put(K key, V value) { if (key == null) return putForNullKey(value); int hash = hash(key.hashCode()); int i = indexFor(hash, table.length); for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(hash, key, value, i); return null; }
首先比較的是HashCode,其次比較的才是equals,如果你只是對equals重寫,沒有重寫hashCode,應該是不會拿到預期後果的。
Java 複習 —— Object