my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why we override hashcode and equal methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why we override hashcode and equal methods" Watch "why we override hashcode and equal methods" New topic

why we override hashcode and equal methods

ramesh gosala

Joined: Sep 30, 2006
Posts: 7
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
Gowher Naik
Ranch Hand

Joined: Feb 07, 2005
Posts: 643

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

Joined: Sep 26, 2006
Posts: 69
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.

hashCode method is required to be overriden when you override equals,
that is a bit complex.. understand the equals first.

Java is better and better, yet bitter and bitter.
I agree. Here's the link:
subject: why we override hashcode and equal methods
It's not a secret anymore!