java - Maintaining hashCode contract for the specific condition, equals() depending on two integers -


i have basic class structure:

class employee { int eid; string ename;  employee(int id, string name) {     this.eid= id;     this.ename= name; } 

the conditions equality such equals() should return true if any of following true:

  1. eid same.
  2. ename same.
  3. lengths of ename same.

i had no problem in overriding equals(), however, in order maintain hash code contract, should override hashcode() well. so, hashcode should depend on eid , ename.length() (if enames equal, lengths equal well). there 4 cases:

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 same value e1, e2, , e3 , different value e4. can't come logic satisfying requirement.

here exact problem:

create class (having parameters name, id etc). show if 2 objects of class compared should return true in of below case :

a. id of both same.

b. name of both same.

c. length of name’s of both same.

make sure hashcode contract should not violate.

you're running trouble because notion of equality inconsistent. specifically, it's not transitive, contract .equals() requires.

it transitive: non-null reference values x, y, , z, if x.equals(y) returns true , y.equals(z) returns true, x.equals(z) should return true.

under definition, e1 equals e2 , e3, e2 not equal e3. incompatible java's notion of equality. why you're running trouble defining reasonable .hashcode() implementation.

however can define custom comparator (or ordering, if you're using guava). use cases (like sorting, searching, or filtering) should able use separate comparator instance .equals() method. trying define equivalent objects, not equal objects.

if can't use separate comparator whatever reason, employee object fundamentally inconsistent, , prove problematic if should "workable" .hashcode() implemented.


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -