| Author |
HashMap and hashCode/equals question
|
Nico Van Brandt
Ranch Hand
Joined: Mar 31, 2011
Posts: 66
|
|
Hi everybody,
I'm learning for the SCJP but while I'm reaching the end of the book, I think I'm starting to get confused and maybe I'm mixing things up...
So my question is the following; Why is it that for the first System.out it won't check the .equals implementation and for the second, it does call .equals?
Does the containsKey method look for == prior looking at .equals or am I just going crazy?
Thanks in advance,
Nico
|
Oracle Java SE6 Certified Programmer
Oracle Java EE5 Certified Web Component Developer
|
 |
Sebastian Janisch
Ranch Hand
Joined: Feb 23, 2009
Posts: 1183
|
|
I'm not 100% sure but i would guess that the containsKey method first invokes == and then equals, since == is the quicker comparison and the contract says that when obj1 == obj2 then obj1.equals(obj2) must return true;
|
JDBCSupport - An easy to use, light-weight JDBC framework -
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
If you check your JDK folder, you'll see a "src.zip" file. Inside you'll find the source code for most of the core API classes. HashMap is one of those.
Below is the code of containsKey and a method it uses. You'll see that it indeed uses == on line 25:
This is probably done to speed things up, but I think it shouldn't be there.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: HashMap and hashCode/equals question
|
|
|