【转】关于String类hashCode方法的几个帖子

1.http://blog.csdn.net/woxueliuyun/archive/2009/02/17/3903102.aspx

 深入了解String,特别是==与hashCode()

 关于==,equal(),在其它很多网站和博客中已经有说明,在这里主要是讲==与hashCode()之间的区别。

    String str1 = "nihao" ;
    String str2 = "nihao" ;
   
    String str3 = new String("nihao");
    String str4 = new String("nihao");
   
    System.out.println("str1==str2: " + (str1==str2));    // true
    System.out.println("str1==str3: " + (str1==str3));    // false
    System.out.println("str3==str4: " + (str3==str4));   // false
   
    System.out.println("HashCode:" + str3.hashCode());  // HashCode:104818427
    System.out.println("HashCode:" + str4.hashCode());  // HashCode:104818427
    
    System.out.println(str3.hashCode() == str4.hashCode());  // true
    System.out.println(str3.equals(str4));  // true

第一个true,是因为str1和str2是同一个变量,这个变量在变量池中。

第一个false,是因为str1在变量池中,而str3在堆栈中,所以是不同。

第二个false,通过new创建的String,是两个不同的对象。

虽然str3和str4是两个不同的对象,但是其hashCode值是一样的,这就和hashCode()函数有关了,下面是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类中,value是该字符串被转换成数组后的对象。由于offset总是为0,所以h一开始就是0。于是只要value是一样的,所 以hashcode一定是一样的。于是可以肯定的说,==在判断对象时,其实是根据对象在堆栈中的地址判断对象是不是一样,而不是根据hashcode 值。

2. http://java.chinaitlab.com/others/773414.html

Java String中的HashCode和equal

    1. hashSet中比较是否重复的依据是a.hasCode()=b.hasCode() && a.equals(b)

    2. String的hashCode依据: 以依赖于char[i]的int值以和char[i]的排列序的算法计算出的。不依赖String的ref.

    3. String的equals依据: a==b || ( a.length=b.length && { a[i]=b[i] } )

    4. 只有用a==b时比校的才是比校的ref,也就是说这时才是比校是a与b是不是同一个对象

    5. 结论: 两个不同ref的String可能会被认为是集合中的同一个元素。

 3.http://hi.baidu.com/songdenggao/blog/item/a7336a607b930d47ebf8f8df.html

关于String.hashCode

 String.hashCode(),提供将任意长的字符串哈希成一个整数。

在Java中,整型数是32位的,也就是说最多有2^32= 4294967296个整数,将任意一个字符串,经过hashCode计算之后,得到的整数应该在这4294967296数之中。那么,最多有 4294967297个不同的字符串作hashCode之后,肯定有两个结果是一样的(这个可以用鸽巢定理来解释,hehe)。

下面的两组,其hashCode就相等了:
http://pic.bandaonews.com/PicView.aspx?id=37219

http://tech.163.com/05/0829/09/1SAIIRG8000915BD.html

http://news.sina.com.cn/c/2005-06-08/10076113241s.shtml

http://news.edw.com.cn/show.aspx?id=3490&cid=25

当用到这样的方法来得到字符串的哈希值,并且此哈希值可能作为系统中的一个比较重要的参数的时候,应该充分考虑到哈希值可能重复的后果并做好一定的容错处理。

原文地址:https://www.cnblogs.com/fzzl/p/1427563.html