Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashCode implementation for class whose all instances are equal

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();
}
like image 948
Natix Avatar asked Feb 24 '14 10:02

Natix


2 Answers

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.

like image 80
Andres Avatar answered Nov 01 '22 17:11

Andres


You could just use the serial version id (cast it down to integer). That will be a unique number for each class.

What you are trying to do doesn't really make a huge amount of sense though without more context being provided. If these objects are stateless then just make them either a singleton (if you do need an instance due for example using them as strategies in a strategy pattern) or make all the methods static if you don't need an instance.

I guess if they are strategies all implementing the same interface then being able to compare them would make sense, but if each implementation is a singleton then the default Object equals and hashCode methods will do everything you need.

like image 23
Tim B Avatar answered Nov 01 '22 17:11

Tim B