Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashMap and hashCode/equals question

 
Nico Van Brandt
Ranch Hand
Posts: 70
IntelliJ IDE Java Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;

 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic