Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# equals method...

Chetan Dodiya
Ranch Hand
Posts: 39
what is the difference between obj1.equals(obj2) and obj1==obj2???
if x.equals(y)is true,then x==y must be true???
AND if x.equals(y)is false,then x==y may be true???

IS x=y is same as x.hashcode()==y.hashcode()???

what is the difference between equals(),== and hashcode() method???

Ankit Garg
Sheriff
Posts: 9509
22
if x.equals(y)is true,then x==y must be true???

Not necessarily, although it can be true

AND if x.equals(y)is false,then x==y may be true???

If equals method is implemented wrongly like using a random number to calculate equality, then it will be false. Under normal circumstances, it will be true.

IS x==y (you forgot one = here) is same as x.hashcode()==y.hashcode()???

No!

Actually equals method is used to check whether two objects are meaningfully equal. Suppose there are two computers on a network with the same name(which is not allowed but let's assume), then they can be called as equals. But they are not == as they are two different machines. If comp1 == comp2 then they are actually the same machine and you are using two different references to point to them. So if == is true (that is you are referring to the same machine) then equals will always be true as the same machine cannot have two names.

You can remember these rules

if == is true, then equals will always be true
if equals is true, then hashCode will always be same

Chetan Dodiya
Ranch Hand
Posts: 39
hey thanks Ankit,
you cleared my all the doubts......

Brian Legg
Ranch Hand
Posts: 488
Well, x==y is not the same as x.hashCode()==y.hashCode() BUT if x==y then x.hashCode() must == y.hashCode(), right?

Ankit Garg
Sheriff
Posts: 9509
22
yes Brian you are right...