| Author |
hashCode, equals, Map
|
Leandro Coutinho
Ranch Hand
Joined: Mar 04, 2009
Posts: 415
|
|
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: 377
|
|
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: 415
|
|
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!!
|
 |
 |
|
|
subject: hashCode, equals, Map
|
|
|