[java]深入到Hashcode内部
在java编程中hashcode(哈希编码)是一个很常见的词。自从java设计者使用了基于哈希算法的散列结构,它就通过哈希编码提供了内部支持。所有的类都从Object类继承了hashcode方法。这个方法返回了一个在32位机器中对于所有对象都唯一的32位整数型数字。
Hashcode 和 == 对于32位机器,当你使用hashcode方法比较2个相同的对象将会得到“真”这个返回值。对于不同的对象这个方法将会返回“假”。
对于64位机器,“==”的使用和hashcode操作开始变得不同,因为hashcode方法返回的是一个32为的整数型数值,而这些数值在64位的体系结构中无法展示在所有内存地址中。这样的情况下,不同的对象就会有相同的哈希编码。然而在64位的机器中,对相同对象的hashcode使用“==”会返回“真”。
下面的代码和输出表明一个对象的hashcode一般是相同的
代码
- package com.example;
- public class Test{
- public static void main(String[] args) {
- Test t = new Test();
- System.out.println(t.hashCode());
- System.out.println(t.hashCode());
- Test t1 = new Test();
- System.out.println(t1.hashCode());
- System.out.println(t1.hashCode());
- }
- }
输出
- 259937031
- 259937031
- 779942019
- 779942019
Hasccode 运算法则
Object类的源码显示了hashcode方法是个本地方法,这就意味这这个方法的代码是使用像c语言之类的低级语言写的。java文档对于Object类的这个方法的实现引用如下:
- As much as is reasonably practical, the hashCode method defined by
- class {@code 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
很少有规则需要java程序员要去遵循(至少理论上是这样)。“等于”和“哈希编码"的重写应当是要遵循的。但是不同的是应当有一个高效的hashcode方法被用于类对象去散列基本的数据结构。事实上,String类重写hashcode方法获得了最好的实践和使用。但是诸如Apache Commons HashBuilder的第三方jar包很容易的处理了hashcode的重写任务和提供了一个很好的实现。
There are few rules which any Java programmer is taught to follow (at least in theory). The equals and hashcode should always be followed.
引用:http://www.javaexperience.com/java-dive-deep-into-hashcode-internals/
g:有些句子真难说通,还要看看长难句理解,有的的长难句还可能没法正确理解其意思,那就更糟了。坚持。。。
转载于:https://blog.51cto.com/orangleliu/1059327