File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "HashMap and hashCode/equals question" Watch "HashMap and hashCode/equals question" New topic

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,


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

Joined: Oct 27, 2005
Posts: 20279

If you check your JDK folder, you'll see a "" 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.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: HashMap and hashCode/equals question
It's not a secret anymore!