• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Hashcode cache query

 
Ranch Hand
Posts: 1376
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Excellent reply. Thanks
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic