How should I implement hashCode()
and equals()
for the following class in Java?
class Emp
{
int empid ; // unique across all the departments
String name;
String dept_name ;
String code ; // unique for the department
}
How should I implement hashCode()
and equals()
for the following class in Java?
class Emp
{
int empid ; // unique across all the departments
String name;
String dept_name ;
String code ; // unique for the department
}
If code is unique (i.e. your business key), it's best to only use the code for equals and hashCode - it's good practice to seperate business key (code) from object id (id).
Here's a nice read: Hibernate Documentation: Equals and HashCode (valid not only for Hibernate itself)
try this code, use
org.apache.commons.lang3.builder
in Eclipse right mouse click-> source -> generate hashCode() and equals() gives this:
I've selected code as a unique field
Guava has helper methods for creating them. You tell it which fields to take in consideration and it will handle nulls for you and do the prime number calculation for hashcode.
IDEs can also generate them based on the fields you choose.
The advantage of delegating it to a tool like that is you get a standard solution and will worry less about bugs and maintenance of varied implementations spread all over your project.
Here's an example of using Guava and generated by an IntelliJ plugin: https://plugins.jetbrains.com/plugin/7244?pr=
equals()and hashcode(),They have a lot of different places. equals(),if we don't Override it from Object,it represent that whether two variables are pointing to the same object heap?
what ever values you use in equals to determine if two objects are the same, are the the values that you need to use to create a hash code.