Pergunta

I have a class that does some pattern matching staff. I stored the pattern in the hashmap using:

private static HashMap<String, String> map = new HashMap<String, String>();  
static {  
    map.put("A", "aba");  
}

This map is intended to provide a map or a dictionary for latter use. My problem is, is there a better way better than using "static" that when I create an instance, I don't have to create the pattern in the hashmap multiple times?

Thanks!

Foi útil?

Solução 2

When using static member variables they are not instantiated every time that the an instance of the surrounding class is instantiated, they are only instantiated once, the first time that the class is loaded.

In your case, assuming that your Map can never change, then it is best to mark it as final, to ensure that it can never change, and wrap it in an unmodifiableMap to ensure that it cannot be modified.

For example:

private static final HashMap<String, String> map;  
static {
    HashMap<String, String> tmpMap = new HashMap<String, String>()
    tmpMap.put("A", "aba");
    map = Collections.unmodifiableMap(tmpMap);
}

Outras dicas

Your static initializer will run just once, the first time your class is loaded. Your static map will be shared by all instances of your class.

Be cautious of thread safety if different instances will edit the map from different threads.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top