javajpahashcodepremature-optimization

Can I cache getClass.hashCode()?


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?
    }
}
  1. Can I cache the value of the getClass().hashCode()?
  2. Is there any possibility of the value being changed while running in a JVM?
  3. Is this some kind of the premature optimization shit?

Solution

    1. Can I cache the value of the getClass().hashCode()?

    You can, but ...

    1. 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.

    1. 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.