Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Immutable - Hashcode() - lazy initialization.

 
Gupta Saurabh
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is said that hashcode() method of the immutable object is common candidate for the lazy initialization.
I think - it is not necessary.
if we are considering it true than can anyone explain with logic behind this phrase.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure what's meant, but let's think about hashcode on different objects.

On a mutable object we'd want to compute hashcode from the current state. The state could change, so if we stored hashcode in a variable for later use we'd have to recompute it any time something changed. That's wasteful because we might never use hashcode again.

On an immutable object, I suppose we could compute the hashcode the first time somebody asks for it and store it for later use. That may be what was meant by lazy initialization.

Does that make sense?
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13061
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here is lazy initialization in action in java.lang.String class


Where hash is a private int initially zero
Bill
 
Gupta Saurabh
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes.. i think it is the perfect answer. thanks james & bill.
actually i missed the part that "hash" could be the member for immutable objects, so somehow could not relate.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic