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?
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])
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With