This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashCode, equals, Map

 
Leandro Coutinho
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 385
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Leandro Coutinho
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic