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 hashCode, equals, Map 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 "hashCode, equals, Map" Watch "hashCode, equals, Map" New topic
Author

hashCode, equals, Map

Leandro Coutinho
Ranch Hand

Joined: Mar 04, 2009
Posts: 417
Hello!

This code is from the K&B SCJP 6:



It explains that the overridden equals() method will view t1 and t2 as duplicates.
I don't understand why. The equals() method use == to compare two strings. So the method should return false, because the strings have the same value, but are two different objects.
What am I missing?

Thanks!
Siva Masilamani
Ranch Hand

Joined: Sep 19, 2008
Posts: 385
No the equals method returns true.

Because String in java is immutable.SO when you create string as Monday java check the string constant pool and if there is such as string it will make a reference to point to that literal else create new one and make the reference to point to it.
In your case the instane variable day of both the objects points to the same string literal and hence the equals method returns true.

Two different string object will be created only if you use new String().

Since both the key are equals its value will be overriden by the last value.

If you print out the value for the key t1 and t2 the output will be payBills


SCJP 6,SCWCD 5,SCBCD 5

Failure is not an option.
Leandro Coutinho
Ranch Hand

Joined: Mar 04, 2009
Posts: 417
Siva Masilamani wrote:No the equals method returns true.

Because String in java is immutable.SO when you create string as Monday java check the string constant pool and if there is such as string it will make a reference to point to that literal else create new one and make the reference to point to it.
In your case the instane variable day of both the objects points to the same string literal and hence the equals method returns true.

Two different string object will be created only if you use new String().

Since both the key are equals its value will be overriden by the last value.

If you print out the value for the key t1 and t2 the output will be payBills

Thank you Siva Masilamani!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: hashCode, equals, Map
 
Similar Threads
S & B SCJP 6 - C7 - Q4 erratum
hashCode()/equals()
How to write toString method to display name of Object
HashMap and hashCode()
Detecting Duplicates in Hashmap