• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding equals() and hashCode()

 
Pradeep Balasubramanian
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the code below



For line #1,
I am getting the output as "dog Key"
For line #3,
I am getting the output as null.

Here, my question is :
"If line #3 is not able to pass the equals() and hashCode() test , how come line #1 is able to pass through them."



 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well first of all the hash code method returns the length of the name, so all the get operations will result in the same hash code as the names that you have used have same length(magnolia, Foxhound).

So now it comes to equals method. the equals method checks two names for equality using == operator. Also remember that the map will store only a reference to the objects in the key and values(I may be wrong here..).

The get operation at #1 succeeds as you are using the same object that you stored as key to retrieve the value.

The condition at #2 must also have succeeded(I think) as the name of d(i.e. Foxhound) and new Dog("Foxhound") are the same.

The condition at #3 fails because at that time the name of d is changed to magnolia and you are trying to get a record where the key has a dog named Foxhound. Again here this will be true if map contains only references to key and value objects and not the objects themselves.

My explanation is not very good I know but this is the best I can do right now. Somebody confirm what I said then I may try to explain it to you further.
 
Sudarshan Chakrabarty
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if ((o instanceof Dog) && (((Dog) o).name == name)) {
return true;
}


You should not be doing a check with instanceOf operator, as this will also return true for any class which is a subclass of Dog.
For e.g. if you have a
public class DoberMan extends Dog {}
and
public class Terrier extends Dog{}
then both your DoberMan and Terrier class will return true for a check
o instanceof Dog, which you would surely not want as DoberMan and Terrier should never be equal.
So, instead of using instanceOf you should be using
if (this.getClass() == o.getClass()) {
return true }

or

if(this.getClass != o.getClass()){return false}

 
chander shivdasani
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As per my understanding, the lines 2 and 3 should print "dog key".

The equals method is overridden in the Dog class, so the Objects "FoxHound" should be equal and as it satisfies both the criteria of Equals and Hashcode.

Can someone put more light on this.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic