Search code examples
javaxmlstringhash

Hash of a String object is 0


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


Solution

  • 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.