Java中的hashCode方法

如果不重写hashCode方法,则我们往HashSet中存入数据时,相同的对象也会存入。但是我查看了下Object的源代码 hashCode方法的源代码是 public native int hashCode();可是即使我们不重写hashCode方法,hashCode方法依然会被调用,只是相同对象得到的哈希码不同而已,但是Object中的hashCode只是一个空方法,又是如何调用的?

第1个回答  2013-09-20
是的,即使我们不重写hashCode方法,hashCode方法依然会被调用。

关于你的问题,英文的维基百科是这么说的 “All the classes inherit a basic hash scheme from the fundamental base class java.lang.Object, but instead many override this to provide a hash function that better handles their specific data. Classes which provide their own implementation must override the object method public int hashCode(). ”

所以java 自己在每个class里面会调用 hashCode 函数,不是空方法,native表示是用其它非java语言写的,使用JNI。
第2个回答  2013-09-20
Object的不是空方法,native 表示是使用C/C++开发的原生方法。本回答被提问者采纳
第3个回答  2013-09-20
通过jni调其它C语言实现的方法