How do you initiate the static fields before the first call of their ghetters?



  • I need access to the statistic fields of the class that should be initiated before their ghetter is called. Like class has a field. private static Map<String, Integer> countryAndId♪ In another class, I need to get the meaning of this field: Map<String, Integer> countryAndId = Countries.getCountryAndId();How am I supposed to make this field (and others) initial to the start of the program automatically and I can just get it? I hope I've explained rightly and easily.


    All right, I've decided a few lines like this:

    static  {
        fillCountryAndId();
    }
    

    In the fillCountryAndId method, the entire initialization code was implemented.

    But there's one "B" thing: this initialization occurs every time I cause a ghetter. How do you start only once? Something like a singlton, did one thing and you use while the program lives? Can we do it in the same singleton, and the fields are not static? Does that sort of solve the problem?

    P.S. I did a singlton class. Works properly, and you need to create an object of singlton, not to cause the static methods of class, as I originally planned.



  • The right thing to do is write.

    private static Map<String, Integer> countryAndId=makeCountryAndId();
    

    The way you wrote

    static  {
        fillCountryAndId();
    }
    

    It's good, too. In both cases, initialization takes place only once.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2