aspose file tools*
The moose likes Java in General and the fly likes HashMap and hashCode/equals question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "HashMap and hashCode/equals question" Watch "HashMap and hashCode/equals question" New topic
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: 19538
    
  16

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 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: HashMap and hashCode/equals question
 
Similar Threads
Please go thru the code
HashMap keys
Question on HashSet
Do I have to override equals() due to using an object as a hashmap key? Yes..but..