Mohammed Shirhaan
Mohammed Shirhaan

Reputation: 553

Generating Hash code based on Equality in Java

I will fetch a list of Objects(Employee entity class) existing in the database to List1. I will be reading list of Objects from an excel sheet to say List2.

Employee entity class will have multiple attributes like, firstName, middleName, lastName, age, phoneNumber, address, SSN, employeeId, etc.

The Object o1 in List1 will be equal to Object o2 in List2 based on any one of the following condition: 1. The firstName, middleName and lastName of o1 and o2 are equal. 2. The SSN of o1 and o2 is equal. 3. The employeeId of o1 and o2 is equal.

If o1 and o2 is equal based on any one of the above condition, it means it should update the attributes like address, phoneNumber etc of o2 to o1. If o1 != o2, then create a new record in database. The above can be achieved using multiple iteration over these lists.

But I am looking for a design to construct 2 HashMaps map1 and map2, one for the existing records (List1) and one for the new records from excel sheet(List2) respectively.

The key for the HashMap should be the HashCode of either [firstName, middleName, lastName] or [SSN] or [employeeId], and the value will be the entire object. So that I can take the Key from map1, and find by key in map2, if exists, update the other attributes from map2 to map1 and save it to database.

Not sure how to build this HashCode method. Is it possible or will it be against the standards?

Upvotes: 0

Views: 153

Answers (1)

Andrzej Jaromin
Andrzej Jaromin

Reputation: 269

The only two standards here are:

  1. If objects are equal, they should have same hashCode (only in this direction) - it is called 'equals-hashcode contract'.
  2. hashCode should depend only on object's fields.

It is not possible to build hashCode correct to the above rules in this case.

Because you can have 3 persons:

  • 1st and 2nd will have same firstName, middleName and lastName
  • 2nd and 3rd will have same SSN but different names

all of these 3 persons should return same hashCode because they're equal. But their hashCode should depend only on fields. The conclusion is - in this case hashCode will depend on context of comparision, not only on fields. What is wrong.

Upvotes: 2

Related Questions