`
什么都不懂的孩子
  • 浏览: 26816 次
社区版块
存档分类
最新评论

java中的hashcode作用

 
阅读更多

根据API文档,java中的hashcode事实上是跟equals是有着密切联系的,hashcode是为了提高哈希表的性能

下面的话来自JDK:

hashCode 
public int hashCode()返回该对象的哈希码值。支持此方法是为了提高哈希表(例如 java.util.Hashtable 提供的哈希表)的性能。

 

public native int hashCode(); 
说明是一个本地方法,它的实现是根据本地机器相关的。当然我们可以在自己写的类中覆盖hashcode()方法,比如String、Integer、Double。。。。等等这些类都是覆盖了hashcode()方法的。例如在String类中定义的hashcode()方法如下: 
   

public int hashCode() { 
      int h = hash; 
      if (h == 0) { 
          int off = offset; 
          char val[] = value; 
          int len = count; 

          for (int i = 0; i < len; i++) { 
                h = 31*h + val[off++]; 
          } 
          hash = h; 
        } 
      return h; 
} 

 
解释一下这个程序(String的API中写到): 
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 
使用 int 算法,这里 s[i] 是字符串的第 i 个字符,n 是字符串的长度,^ 表示求幂。(空字符串的哈希码为 0。) 

 

在集合中,比如HashSet中,要求放入的对象不能重复,那么首先会调用hashcode,如果hashcode相等,则继续调用equals,也相等,则认为重复。

如果重写equals后,如果不重写hashcode,则hashcode就是继承自Object的,返回内存编码,这时候可能出现equals相等,而hashcode不等,你的对象使用集合时,就会等不到正确的结果

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics