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


Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 528

Hi all,

in Khalid's book he overrides the equals() method like this (basically):

public boolean equals(Object obj){

if(obj == this)


I don't understand one thing though, wouldn't the above check to see if they refer to the same object instead of checking for their meaningful value? The equals() method in the Object class already does this though?


Live life to an interface, not an implementation!
prithvi s zankat

Joined: Jul 18, 2005
Posts: 12
Yes exactly. The equals() Object method is for checking the same object and not for checking the contents of the object. Although in the special case of <String> it overrides this method for checking the actual content of the string.
Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 528

i don't entirely agree with your reply, because K&B checks the content of the objects with their most signigicant fields.

can anyone plz explain this to me?
Marcos Vilela

Joined: Jul 06, 2005
Posts: 18
if you don't override the equals() you are going to compare the objects reference, ==, as it was implemented in Object class, but you can override equals() an compare the object in the way you want. For example with the most important field...

Mahesh Kumar Kumar

Joined: Jul 14, 2005
Posts: 8
Correct me if I am wrong, but isn't equals(Object) method supposed to use hasCode() method. If the hash codes are same then the equals method returns true?

Thanks in advance.
Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 528

No. If the hashCode for two given objects are the same, they do not have to be equal. But, if the two objects ARE equal (acording to the equals() method), then they SHOULD have identical hashCode values (acording to the contract).
I agree. Here's the link:
subject: equals()
It's not a secret anymore!