Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill HashMap object only once for program?

Given the following portion of my wider program:

public class AnimalNames {
  private static String[] animalNames = {dog, cat, horse, cow, donkey, elephant};
  private static String[] animalNameAbbreviations = {d, c, h, co, d, e};
  public static HashMap<String, String> getAnimalNameTranslations() {
    HashMap<String, String> animalNameTranslations = new HashMap<String, String>();
    for (int i = 0; i < animalNames.length; i++) {
      animalNameTranslations.put(animalNameAbbreviations[i], animalNames[i])
    }
    return animalNameTranslations;
  }
}

I'm able to access the filled animalNameTranslations (using the static keyword) without instantiating the AnimalNames class, which is what I want. However, my program still has to fill animalNameTranslations every time I want to access it (using the for loop). Is there a way to fill the HashMap object only once for my program?

like image 635
danger mouse Avatar asked Jan 09 '23 06:01

danger mouse


1 Answers

You can call the getAnimalNameTranslations method from your static initializer block, which would be executed once, when the class is initialized. You'll have to add a static member that holds the Map returned by the method.

For example :

private static HashMap<String, String> animalNameTranslations;
static {
    animalNameTranslations = getAnimalNameTranslations ();
}

Or just move the logic of that method directly to the static initializer block.

  private static HashMap<String, String> animalNameTranslations;
  static {
    animalNameTranslations = new HashMap<String, String>();
    for (int i = 0; i < animalNames.length; i++) {
      animalNameTranslations.put(animalNameAbbreviations[i], animalNames[i])
    }
  }
like image 180
Eran Avatar answered Jan 10 '23 20:01

Eran