简体   繁体   English

如何在Java中多次避免哈希图中的加载模式

[英]How to avoid load patterns in hashmap multiple times in java

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! 谢谢!

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. 如果不同的实例将从不同的线程编辑映射,请谨慎考虑线程的安全性。

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. 在您的情况下,假设您的地图永远不会更改,那么最好将其标记为最终地图,以确保它永远不会更改,然后将其包装在unmodifiableMap中以确保它不能被修改。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM