Search code examples
javahibernatejpahashhashcode

Is there any reason for returning constant value from hashCode method?


I have a question related to extensively discussed topic about hashCode method from java.lang.Object. Simply is there any reason why I should in some use-case return a constant value from hashCode()?

public int hashCode()
{
   return 3;
}

If you found some article or SO thread which directly answers my question I'd appreciate it. Frankly speaking I couldn't.

My thoughts:

From docs.oracle.com object hashCode() (I know quoted many many times here in SO):

It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables."

So in theory hashCode() can return a constant value. In my imagination and what I've read, all objects then will be placed in the same bucket when using for example HashMap. As an example lets say 1000 elements will be placed in exactly the same hash bucket (there will be 1000 collisions then in the other words) and to find specific one in the wrong case scenario that 1000 elements would have to be iterated. Then it will perform similarly to LinkedList collection (correct me if I am wrong please).

Basing on the above, hashCode() can return a constant value like, but it will destroy performance gained from using hash... collections. Is there any sense then to do it in some particular example?

EDIT: I found one particular example for having constant hashCode method basing on Vlad's Mihalcea article: How to implement equals and hashCode using JPA entity identifier, (Hibernate). HashCode differs between entity state transitions, hence it should return constant value. Quote from the article:

When the entity was first stored in the Set, the identifier was null. After the entity was persisted, the identifier was assigned to a value that was automatically generated, hence the hashCode differs. For this reason, the entity cannot be found in the Set after it got persisted.

So there is a practical example, but as it is pointed out at the cost of performance. If there is a business unique not null identifier apart from entity id, it is better to use it in order to take an advantage of storing entities in the multiple Hash... buckets.


Solution

  • Generally you would never return a static member when overriding hashcode. I've never done this before but the only possible use case I could even imagine would be singletons where you expect runtime to only ever have 1 instance that is not lazily initialized. This is kind of useless because if you design the class to use the singleton pattern you should never need to use equals/hashcode.