关于hashcode的介绍----java2核心思想

来源:互联网 发布:grub4dos linux 编辑:程序博客网 时间:2024/05/28 17:06

hashcode方法是在Object类中定义的,因此,每个对象有一个默认的代码。那个hash代码是来源于对象的内存地址。

思考一下下面的这个例子

String s = "Ok";
StringBuffer sb = new StringBuffer(s);
System.out.println(s.hashCode() + " " + sb.hashCode());

String t = new String("Ok");
StringBuffer tb = new StringBuffer(t);
System.out.println(t.hashCode() + " " + tb.hashCode());

下面就是上面这个程序的运行的结果

Object

Hash Code

s

3030

sb

20526976

t

3030

tb

20527144


String类用下面的算法来计算其hashcode:

int hash = 0;
for (int i = 0; i < length(); i++)
   hash = 31 * hash + charAt(i);


也就是说对于String而言,它的hashcode来源它的内容,在stringbuffer sb和tb之所以拥有不同的code是因为hashcode方法没有在StringBuffer中定义,默认的方法是来源于在Object中定义的方法,这个方法对于hashcode的算法是基于对象在内存中的地址的。