File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Immutable - Hashcode() - lazy initialization. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Immutable - Hashcode() - lazy initialization." Watch "Immutable - Hashcode() - lazy initialization." New topic
Author

Immutable - Hashcode() - lazy initialization.

Gupta Saurabh
Greenhorn

Joined: Dec 22, 2006
Posts: 4
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.


~Regards<br />Saurabh Gupta
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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?


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12761
    
    5
here is lazy initialization in action in java.lang.String class


Where hash is a private int initially zero
Bill
Gupta Saurabh
Greenhorn

Joined: Dec 22, 2006
Posts: 4
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Immutable - Hashcode() - lazy initialization.
 
Similar Threads
Doubt in Effective Java
Lazy Initialization
Hashcode doubt
General
Strign.replace() replaceAll()