Java中hashCode()返回常量值是否存在合理应用场景?
hashCode() makes sense? Absolutely, there are edge cases where returning a constant from hashCode() is not just allowed by Java's rules, but even necessary—though it comes with clear performance tradeoffs you’ll need to weigh carefully.
First, the Java Contract Perspective
Per the official Object class documentation (a reference you’ll see cited constantly on Stack Overflow):
If two objects are equal according to the
equals(Object)method, then calling thehashCodemethod on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to theequals(Object)method, then calling thehashCodemethod 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 returning a constant like 3 from hashCode() is fully compliant with the contract. The catch is the performance hit you correctly identified:
- All objects will land in the same bucket in hash-based collections (like
HashMap,HashSet). For 1000 elements, that means 1000 collisions. - Worst-case operations (lookups, inserts, deletes) degrade to O(n) time—on par with a
LinkedList—so you lose the O(1) average performance that makes hash collections useful.
A Real-World Edge Case: JPA/Hibernate Entities
The most common practical scenario where a constant hashCode() is recommended is for JPA entities during their lifecycle state transitions, as explained by Hibernate expert Vlad Mihalcea:
When an entity is first added to a
Set, its identifier is null. After persistence, the identifier gets assigned an auto-generated value, which would change thehashCode()if it's based on the ID. This makes the entity unfindable in theSetafter persistence.
In this case, returning a constant hashCode() prevents the entity from becoming "lost" in hash collections once its auto-generated ID is populated. That said, there's a better alternative if you can use it:
- If your entity has a non-null business unique identifier (a field that doesn't change throughout the entity's lifecycle, not the auto-generated ID), use that to compute
hashCode()instead. This keeps the hash value consistent and maintains the performance benefits of hash collections.
Final Takeaways
- Returning a constant
hashCode()is technically valid, but it should be a last resort. - It’s only justified when consistency of the hash value is critical—even at the cost of hash collection performance.
- JPA entities with auto-generated IDs are the primary example of this edge case.
内容的提问来源于stack exchange,提问作者jwpol

