HashCode implementation for a class with all instances equal

Suppose I have a class where all instances are considered equal. A typical use case is for classes that have no state, but only behave like 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 to implement the hashCode method? Naturally, this must be a constant value in order to comply with the equals / hashCode contract. But what should it be? If some trivial value is used, such as 0 or 1, this can lead to collisions with other similar classes.

So, it seems like it comes down to the question: how to implement hashCode, which may be unique for a given class, but the same for all its instances.

I came up with these two ideas. Do you think they are sane?

 @Override public int hashCode() { return ToStringFunction.class.hashCode(); } @Override public int hashCode() { return "ToStringFunction".hashCode(); } 
+6
source share
2 answers

If the class has no state, it must be a singleton, an abstract class, or a repository of static methods (e.g. Math). Therefore, it makes no sense to redefine equal and hash codes for it.

+6
source

You can simply use the serial version identifier (drop it to the integer). This will be a unique number for each class.

What you are trying to do does not really make much sense, but without additional context. If these objects do not have a status, then simply make them either single (if you need an instance, for example, using them as strategies in the strategy template), or make all methods static if you do not need an instance.

I think if they were strategies that implement the same interface, then the possibility of comparing them would make sense, but if each implementation is a single, then the default methods equals and hashCode will do everything you need.

+1
source

All Articles