String对象的哈希值为0

rav*_*svi -2 java xml string hash

场景:有一个消息发送者和一个消息接收者.消息的内容将转换为xom.nu文档并传递给接收方.有趣的事发生在这里.其中一个标签(即文本)有一个属性(语言),其值为字符串"en".

发送方的"en"具有哈希值,但接收方的哈希值显示为零.是什么导致字符串的哈希值为零?

发件人:

发件人图片http://i41.tinypic.com/313rh4p.png

接收器:

Receiver Image http://i43.tinypic.com/izyjpg.png

Joa*_*uer 8

您不应仅通过其内部检查变量.

在这种情况下,您的问题是该字段hash充当缓存.它只包含一个值,如果hashCode()曾在此实例上调用过.

尝试观看yourVariable.hashCode(),你会注意到这个hash领域也会发生变化.


Den*_*ret 5

这是hashCode方法的来源:

1493    public int hashCode() {
1494        int h = hash;
1495        if (h == 0) {
1496            int off = offset;
1497            char val[] = value;
1498            int len = count;
1499
1500            for (int i = 0; i < len; i++) {
1501                h = 31*h + val[off++];
1502            }
1503            hash = h;
1504        }
1505        return h;
1506    }
Run Code Online (Sandbox Code Playgroud)

您会看到该值仅在您(第一次)调用hashCode. 这与hash 私有无关:您只能使用该hashCode方法正常获取它。

回答您的明确问题:字符串的散列(由 返回hashCode)适用0于空字符串(但不仅适用于空字符串)。