Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equal and hashCode with non primitive types

Tags:

java

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

  1. the name are equal
  2. the role type (identified by unique typeName) are equal for the Role members (roleFrom and roleTo)

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.

like image 424
bsr Avatar asked Dec 23 '22 00:12

bsr


2 Answers

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).

like image 185
Bozho Avatar answered Jan 12 '23 00:01

Bozho


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.

  • http://java.sun.com/javase/6/docs/api/java/lang/Object.html#equals%28java.lang.Object%29
  • http://java.sun.com/javase/6/docs/api/java/lang/Object.html#hashCode%28%29
  • http://www.javaworld.com/javaworld/jw-06-2004/jw-0614-equals.html
like image 44
Jose Diaz Avatar answered Jan 11 '23 23:01

Jose Diaz