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?
}
}
- Can I cache the value of the
getClass().hashCode()? - Is there any possibility of the value being changed while running in a JVM?
- Is this some kind of the premature optimization shit?
You can, but ...
No possibility. The class of a Java object cannot change, and the hashcode of a Java
Classobject (which is the result type forgetClass()) cannot change.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 mostHashSetandHashMapoperationsO(N)orO(logN)(depending on your Java version) rather thanO(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::hashCodemethod is not overridden to something more sensible by concrete subclasses ofSome.