I have (at least) two classes that implement the same interface and have the same fields. Is it ok if those two classes have the same hash code if their fields are identical or should they be different? Is this code ok?
interface Base { }
class A implements Base {
private Integer value;
public A(Integer value) { this.value = value; }
public int hashCode() { return value.hashCode(); }
}
class B implements Base {
private Integer value;
public B(Integer value) { this.value = value; }
public int hashCode() { return value.hashCode(); }
}
hashCodeimplementations if it makes sense for both of them. Though from your question it's somewhat unclear what the purpose of these two classes is.hashCodeis thatA.equals(B) ==> A.hashCode() == B.hashCode(). Also: you should always modify bothhashCodeandequalstogether to keep that requirement... Obviously doing this will have implications. For example Python does this with numbers classes so that integer1is equal to float1.0, but this implies that if you have a map like{1: "a"}then you can use1.0in place of1to fetch that value and you cannot have both1and1.0as keys since they are effectively identical for the hashmapMaporSetcontaining instances of both classes. But you could also just add the hashcode of the class itself to the instances' hashcodes.