Roam
Roam

Reputation: 4949

hashCode() value changes between executions

hashCode of an object has to be consistent for that object throughout one execution of the application-- for any object o, o.hashCode() should return the same int value.

However, this doesn't have to be from one run-time to another: o.hashCode() can return some other value and this is perfectly alright by the specs.

HashMap calculates the right bucked based on the hashCode value.

My Q is: how is this value change between one session to another handled? Does serialization have features to handle this?

So, suppose I built a hash and stored it on the disk. 2 weeks after, I invoked the application and am running it. I'm looking up an object in the hash. By these, the hashCode of this object is/can be now different than before and I wont be able to find it although it is there in the hash.

Upvotes: 4

Views: 2522

Answers (3)

Jason C
Jason C

Reputation: 40336

The general contract of Object.hashCode() does, as you say, specify that the hash code can change between runs.

However, if you require a hash code that does not change between runs, it is simply up to you to override hashCode() with your own implementation that guarantees that.

Your application requirements impose additional rules, but these do not break the general Object.hashCode() contract. Therefore, you can safely implement your own hashCode() that meets your requirements here without risk of breaking anything else. Note that hashCode() does not require hash codes to differ between runs, it merely allows it.

The reason, by the way, that the spec allows this is because the base implementation just returns the memory address of the object, which can differ between runs. This is sometimes appropriate for quick, one-off uses but generally isn't. You usually want to implement a hashCode() that computes a hash code based on business values, that is consistent between runs and that is the same for objects that are equal at the business level (i.e. two Integer instances that have the same value).

As Robin Green pointed out, Java's HashMap implements custom serialization that is independent of the hash value of the object at the time of storage. However, if you were to implement your own hash table, and simply stored hash values of objects, you would not be guaranteed that you could find the object after deserializing your hash table (unless of course you only stored objects in it with a consistent hashCode()).

Upvotes: 2

dimoniy
dimoniy

Reputation: 5995

When you serialize the hashtable, you serialize values, not hash codes. Serializing hash code is a bad idea.

Upvotes: 1

Robin Green
Robin Green

Reputation: 33063

This works because hashtables are not serialized as hashtables. They are serialized in a custom way. So when deserialized, the hashtable will be rebuilt using the new hashcodes.

Upvotes: 7

Related Questions