• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

why we override hashcode and equal methods

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic