• Post Reply Bookmark Topic Watch Topic
  • New Topic

Hashcode cache query  RSS feed

 
Abhay Agarwal
Ranch Hand
Posts: 1376
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
It is said that hashCode values can be cached if we use immutable keys in HashMap.
I want to know
a. what is the advantage of caching done by JVM for keys ??
b. how caching is done by JVM for keys ??

Thanks
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The JVM, or HashMap, does not automatically cache hash codes of your keys. You have to do that yourself, in the implementation of the hashCode() method of the objects that you use as keys.

Why you would want to do that: For performance optimization; if an object is immutable, its hash code should always be the same, so you don't need to compute it every time hashCode() is called. So, it's to avoid unnecessary computations.

How it is done: You have to do it in the implementation of your hashCode() method, the JVM isn't doing this automatically for you, because the JVM doesn't know if your objects are immutable or not.

Keys in a Map should always be immutable, but it's your job to make sure that is so - the JVM or the Java compiler can't force you to make your key objects immutable.
 
Abhay Agarwal
Ranch Hand
Posts: 1376
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent reply. Thanks
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!