As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
对于Java中的hashcode默认实现,引用Object中hashcode方法的javadoc原文:
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct
objects. (This is typically implemented by converting the internal
address of the object into an integer, but this implementation
technique is not required by the JavaTM programming language.)
简单的翻译一下:就是hashcode是通过将内部存储地址映射成一个整型值,这个整型值就是hashcode。java语言规范对hashcode的实现不做要求,这是JVM的实现。需要注意的是:
对于有些架构(例如64位),内存地址空间超过int的表示范围,所以不同对象地址的映射值必然会有相同的,所以hashcode不能确定两个是否相等
对于C#,Object.GetHashCode方法的实现同样是基于对象引用(其实就是对象的内部存储地址)来计算。而且MSDN文档同样明确表明:
.NET Framework 不充当防护措施 GetHashCode 方案的默认值实现,因此,此方法返回的值可能不同于 .NET Framework 版本和平台之间,如 32 位和 64 位平台。
具体可参考MSDN-Object.GetHashCode
不管是Java还是C#,hashcode都是应用于hash数据结构。基本上很少使用默认实现,都是用来重载的,而且二者对hashcode重载的规范也是一致:
1. 如果两个对象equal,则hashcode必须一致;
2. 如果两个对象的hashcode一致,但两个对象不一定equal;