HashCode implementation for class whose all instances are equal

equality, hashcode, java

Solution

If a class does not have state, it should be a singleton, an abstract class, or a repository of static methods (like Math). Therefore, it makes no sense to override equals and hashcode for it.

Problem

Suppose I have a class where all instances are considered equal. A typical use case is for classes that do not have any state, but only behave as functions. ``` public class ToStringFunction implements Function<Object, String> { @Override public String apply(Object o) { return o.toString(); } @Override public boolean equals(Object o) { return o instanceof ToStringFunction; } } ``` Now, how should one implement a hashCode method? Naturally, it needs to be a constant value in order to honor the equals/hashCode contract. But what value should that be? If some trivial value such as 0 or 1 was used, it could lead to collisions with other similar classes. So it seems that this boils down to the question: how to implement a hashCode that is likely to be unique for a given class, but the same for all of its instances. I came up with these two ideas. What do you think, are they sane? ``` @Override public int hashCode() { return ToStringFunction.class.hashCode(); } @Override public int hashCode() { return "ToStringFunction".hashCode(); } ```

Original source