Home > programming > Lazy initialization

Lazy initialization

Lazy initialization has two objectives :

  • delay an expensive operation until it’s absolutely necessary
  • store the result of that expensive operation, such that you won’t need to repeat it again

import java.util.*;

public final class Athlete {

  public Athlete(int aId){
    //a toy implementation:
    fId = aId;
    fName = "Roger Bannister";
    //fAwards is not set here!


   Lazy initialization is used here; this assumes that awards
   may not always be of interest to the caller,
   and that for some reason it is particularly expensive to
   fetch the List of Awards.
  public List getAwards(){
    if ( fAwards == null ) {
      //the fAwards field has not yet been populated
      //Here is a toy implementation
      List awards = new ArrayList();
      awards.add( "Gold Medal 2006" );
      awards.add( "Bronze Medal 1998" );
      fAwards = awards;
    return fAwards;

   This style applies only if the object is immutable.
   Another alternative is to calculate the hashCode once, when the 
   object is initially constructed (again, applies only when object is 
  @Override public int hashCode(){
    if ( fHashCode == 0 ) {
     fHashCode = HashCodeUtil.SEED;
     fHashCode = HashCodeUtil.hash(fHashCode, fId);
     fHashCode = HashCodeUtil.hash(fHashCode, fName);
     //self-encapusulated: fAwards is not referenced directly, 
     //since it may be null:
     fHashCode = HashCodeUtil.hash(fHashCode, getAwards());
    return fHashCode;

  // PRIVATE //
  private int fId;
  private String fName;
  private List fAwards;
  private int fHashCode;

Categories: programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: