java - How to fill HashMap object only once for program? -


given following portion of 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>();     (int = 0; < animalnames.length; i++) {       animalnametranslations.put(animalnameabbreviations[i], animalnames[i])     }     return animalnametranslations;   } } 

i'm able access filled animalnametranslations (using static keyword) without instantiating animalnames class, want. however, program still has fill animalnametranslations every time want access (using loop). there way fill hashmap object once program?

you can call getanimalnametranslations method static initializer block, executed once, when class initialized. you'll have add static member holds map returned method.

for example :

private static hashmap<string, string> animalnametranslations; static {     animalnametranslations = getanimalnametranslations (); } 

or move logic of method directly static initializer block.

  private static hashmap<string, string> animalnametranslations;   static {     animalnametranslations = new hashmap<string, string>();     (int = 0; < animalnames.length; i++) {       animalnametranslations.put(animalnameabbreviations[i], animalnames[i])     }   } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -