I have a class with some non primitive members.
class Relation {
String name;
Role roleFrom;
Role roleTo;
}
class Role {
RoleType roleType;
String details;
}
class RoleType {
String typeName;
String details;
}
Two relations are equal, when
How to write equals
and hashCode
for class Relation
. When tried with Netbeans, it only displays 3 fields (name
, roleFrom
and roleTo
). Is it because, one should not access the primitive types in roleFrom and roleTo (roleType -> typeName). Or, please show an implementation.
thanks.
When implementing hashCode()
and equals()
with non-primitive types of fields, it is assumed that these types also implement hashCode()
and equals()
correctly. So go to the other classes and implement hashCode()
and equals()
there (again using the auto-generation features of your IDE).
You should be extremely careful when overriding your equals
method, the best thing to do, as noted by Joshua Bloch in "Effective Java" is not to override it at all unless it is absolutely necessary, with the default equals implementation inherited from java.lang.Object every objects is only equals to itself.
I recommend that you check the following links to learn how to appropriately implement both your equals
and hashCode
methods. The last link shows you how to implement those methods when you have non primitive types as well as considerations for when you're dealing with inheritance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With