1

I have questions while implementing the hashmap for customized Employee class.

  1. Overriding only Hash()

    I have overridden only hash() of employee class. so, I get same hashcode value for same objects. If I don't override equals(), then it would be fine right? since the equals() of object class compares the reference (where I got the same ref for equal objects). Anyhow, based on my logic, I will never get same hash for different emp objects. So it would be fine to leave the equals()?

  2. If we override both Equals() and hashcode(), then we will always have unique value? so there won't be the possibility of getting Linkedlist in a single bucket location?

  3. When we override the equals(), in first line we will always give (this == o). In this case, Even after overriding the hashcode(), if i get same hashcode for 2 diff employee object, the first line will always gets satisfied if same hashcode returned. Then what is the use of having the remaining logic in equals()?

1 Answer 1

0

You can have the same hashcode and different equals for two objects. hashcode doesn't have to be unique. Even if all objects will return the same hashcode if will not damage the logic, but of course will be inefficient in terms of performance. The opposite is of course forbidden two objects that are equals but have different hashcode will lead to inconsistency. Example of a bad behaviour: You can put an object in a HashMap, but then when you retrieve a same object (a one that equals to the first) you will not get it since it has a different hashcode.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.