I write something like a calculator. You need to create a container that stores operations (+, -, *, etc).
I think to store them in static final HashSet , but I cannot understand how to create and immediately initialize the container in the class. In C++ I would use the initialization list, but as far as I understood, they are not in Java .
How to do it?

  • why not just use an array? - Mikhail Vaysman
  • @MikhailVaysman When parsing an input string, searching through an array will take significantly longer than over a set - sm4ll_3gg
  • Where do you get this data from? did you make a benchmark? - Mikhail Vaysman
  • @MikhailVaysman This is obvious - sm4ll_3gg
  • one
    you are doing premature optimization - that’s obvious. in your case, the opposite situation is likely - as there is little data. - Mikhail Vaysman

1 answer 1

You can initialize this object using:

  • static block

     private static final Set<String> set; static { set = new HashSet<>(); } 
  • static method

     private static final Set<String> set = init(); private static Set<String> init() { return new HashSet<>(); } 
  • double {}

     private static final Set<String> set = new HashSet<String>() {{ add("+"); }}; 
  • I note that in the third case, an anonymous heir from HashSet , and in rare cases it can lead to undesirable behavior. - Nofate