Whatever the reason, I have the following hashCode implemented in my abstract class.
@MappedSuperclass
abstract Some {
@Override
public boolean equals(final Object obj) {
// ...
}
@Override
public int hashCode() {
return getClass().hashCode(); // TODO: cache, maybe?
}
}
getClass().hashCode()?
- Can I cache the value of the
getClass().hashCode()?
You can, but ...
- Is there any possibility of the value being changed while running in a JVM?
No possibility. The class of a Java object cannot change, and the hashcode of a Java Class object (which is the result type for getClass()) cannot change.
- Is this premature optimization?
Probably yes1.
However, using the hashcode of the object's class as the hashcode of an object is a very bad idea from a performance perspective.
Doing that means that all instances of the class (e.g. Some) will have the same hashcode2. That will lead to a bazillion hash collisions, and make most HashSet and HashMap operations O(N) or O(logN) (depending on your Java version) rather than O(1).
1 - I am assuming you have not done a bunch of performance analysis that you haven't told us about. If you had already done the analysis, then maybe this is not a premature optimization.
2 - I am assuming that the Some::hashCode method is not overridden to something more sensible by concrete subclasses of Some.