File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes equals method... 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 "equals method..." Watch "equals method..." New topic
Author

equals method...

Chetan Dodiya
Ranch Hand

Joined: Jun 27, 2008
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???


SCJP 1.5
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9302
    
  17

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


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Chetan Dodiya
Ranch Hand

Joined: Jun 27, 2008
Posts: 39
hey thanks Ankit,
you cleared my all the doubts......
Brian Legg
Ranch Hand

Joined: Nov 07, 2008
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?


SCJA
~Currently preparing for SCJP6
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9302
    
  17

yes Brian you are right...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: equals method...