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(); }
Natix source share