Java – hashcode contract that maintains specific conditions, and equals () depends on two integers
I have a basic structure class:
class Employee { int eId; String eName; Employee(int id,String name) { this.eId= id; this.eName= name; }
Equals() should return true if any of the following conditions are met:
>Eid is the same. > Ename is the same. > Ename has the same length
I have no problem overriding equals (), but in order to maintain the hash code contract, I should also override hashcode () Therefore, hashcode should depend on Eid and ename Length() (if enames are equal, they will be equal in length) So there are four situations:
Employee e1 = new Employee(4,"John"); Employee e2 = new Employee(3,"Jane"); Employee e3 = new Employee(4,"Jim"); Employee e4 = new Employee(7,"Random");
Hashcode() should return the same values of E1, E2 and E3 and different values of E4 I can't think of the logic to meet this requirement
This is the exact question:
Solution
You're in trouble because your concept of equality is inconsistent Specifically, it is not transitive Contractual requirements for equals ()
According to your definition, E1 is equal to E2 and E3, but E2 is not equal to E3 This is incompatible with the concept of equality in Java This is what you are defining reasonably The reason why hashcode () has trouble implementing
However, what you can do is define a custom comparator (or ordering, if you are using guava) For most use cases (such as sorting, searching, or filtering), you should be able to use The equals () method uses a separate comparator instance You are effectively trying to define an equivalent object instead of an equivalent object
If you cannot use a separate comparator for some reason, your employee objects will be basically inconsistent, even if you should implement "feasible" Hashcode() can also cause problems