2013-02-28 178 views
40

如果不覆蓋hashCode方法,hashCode的默認實現是什麼?「hashCode」的默認實現是什麼?

+0

關於默認impl ementation你可以閱讀[this](http://blogs.tedneward.com/CommentView,guid,eca26c5e-307c-4b7c-931b-2eaf5b176e98.aspx) – CAMOBAP 2013-02-28 08:39:21

+1

默認實現是JVM特定的,但是一般來說它返回'return Objects。散列(this.field1,this.field2,this.field3等);' – NoName 2017-06-24 06:19:06

回答

38

然後這個類從它的一個祖先繼承hashCode。如果它們沒有覆蓋它,則使用Object.hashCode

docs

多達是合理可行,由Object類定義的hashCode方法並返回不同的整數爲不同的對象。 (這一般是通過將該對象的內部地址轉換成一個整數來實現的,但不是由的JavaTM編程語言不需要這種實現技巧。)

所以默認實現是JVM特異性

+0

謝謝,是的。 Object.hashCode()的實現看起來像什麼? – 2013-02-28 08:29:23

+1

@JohnThreepwood它是一個實現細節,您需要爲此解決您的JVM文檔。 – 2013-02-28 08:32:49

+2

http://stackoverflow.com/a/32454673/6785908 – 2017-03-11 23:27:11

3

對象。 hashcode()是一種本地方法。

public native int hashCode();

這意味着它在特定於平臺的代碼實現的,公開爲本地方法。對於同一

代碼將是編譯代碼,而不是提供withing JDK

existing question可能會提供更多的信息。

14

默認情況下,未覆蓋的方法從Object繼承。

如果您查看該方法的文檔,返回值是「[...] distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer [...])」。 java.lang.Object中的方法被聲明爲native,這意味着該實現由JVM提供,並可能因您的運行時環境而異。

一個小例子:

Object o1 = new Object(); 
Object o2 = new Object(); 
System.out.println(o1.hashCode()); 
System.out.println(o2.hashCode()); 

打印(使用我JDK6):

1660187542 
516992923 
hashCode()值的

十六進制表示法中的方式的默認實現的toString()用於:運行System.out.println(o1)打印類似

[email protected] 
+0

很好的解釋。 – chipmunk 2014-10-28 21:30:04