1

Scenario: There is a message sender and a message receiver. The contents of the message are converted into a xom.nu document and passed to the receiver. Something funny happens here. There is an attribute (language) for one of the tags, i.e text, whose value is a string "en".

The sender's "en" has a hash value but the receiver's hash is shown to be zero. What causes the hash of a string be zero?

Sender:

Sender Image

Receiver:

Receiver Image

Community
  • 1
  • 1
ravisvi
  • 149
  • 2
  • 9

2 Answers2

10

You should not inspect a variable only by its internals.

In this case your problem is that the field hash is acting as a cache. It only contains a value if hashCode() has ever been called on this instance.

Try watching yourVariable.hashCode() and you'll notice that the hash field will change as well.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
5

Here's the source of the hashCode method :

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    }

You see that the value is computed only when you (first) call hashCode. Which doesn't matter as hash is private : you can only get it normally using the hashCode method.

To answer your explicit question : the hash of a string (as returned by hashCode) is 0 for empty strings (but not only for empty strings).

Community
  • 1
  • 1
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758