Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why we override hashcode and equal methods

 
ramesh gosala
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi....I have doubt regading Hashcode and equal methods

why we override this two methods....
why we override hashcode method when we are overriding equal method,
i would very thankful to give answser

Thank you
Ramesh
 
Gowher Naik
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Check code Above
in above code i have created two instances of Equal class
at line 9 and 10.
I as developer decided that two objects of Equal class are equal if both
class have same id(line 2)
Now when i use equals method(line 11) it shows that e1 and e2 are
different(see o/p).
I get o/p "Not Equal" because i have not override equal method in
Equal class.
So if i want two class with same id should be equal according
to equal method then i should override equal method in my class.

hashCode method is Linked with equal method first understand
equal method then see why we need to override hashCode method using maps.
 
William Yan
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you make new class, say Dog.


When you make 2 objects with the same weight, and invoke equals method

it will give you false. Because the equals is a method you inherit from Object. in equals of Object, it simple estimate if the two references refer to the same object. And a and b refer to different Dog objects. So you get false.
To solve that, you should override the equals method.
say:

hashCode method is required to be overriden when you override equals,
that is a bit complex.. understand the equals first.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic