-1
String str="abc";
for (int i = 0; i < 100; i++)
{
  System.out.println(str.hashCode());
}

1) String is an immutable class and its hashCode is cached in its private variable hash.

2) Since string str is a literal this string object created is added to stringpool in permgen space. So when ever referencing str it should give me the same object.

Debugging through the process in hashCode method of string, based on above two points when i call str.hashCode() it should enter into calculating the hash only once and the next 99 times it should return me the "cached hash private variable of the string object". It doesnt go according to the point 1. Can some one please let me know about this behavior?

Debugging through this you will notice that hashCode is calculated 100 times and I am printing hashCode value to see if the objects are have same hashCode.

4

3 回答 3

1

hashcode只计算一次,请看java.lang.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;
    }

第二次,你调用str.hashCode()的变量h不是0if并且语句的主体没有被执行。

于 2012-07-24T16:13:10.840 回答
1

java.lang.String 类对象确实缓存哈希值。它在第一次调用 hashcode 时分配实例变量 hash,见下文:

public int hashCode() {
        int h = hash;
        if (h == 0 && count > 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;
    }

任何对哈希码的进一步请求只是通过哈希返回 h,跳过计算。它就在我可以看到的代码中!

于 2012-07-24T16:11:27.210 回答
0

我的错。

发生的事情是因为当您开始调试时我在 hashCode 中有断点,所以我的 forloop 没有调用 hashCode 方法,但某些系统初始静态方法正在调用 String hashCode 方法。

管理员请关闭问题

于 2012-07-26T19:04:47.023 回答