This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "equals()" Watch "equals()" New topic
Author

equals()

Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 519

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?


SCJP 1.4, SCWCD 1.4, SCBCD 1.3, SCJD, SCEA/OCMJEA

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

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: 519

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
Greenhorn

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
Greenhorn

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: 519

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: http://aspose.com/file-tools
 
subject: equals()
 
Similar Threads
equals( ) & ==
instanceof
Understanding .equals
equals()
StackOverflowError using hashCode() in HashMap in recursive method