簡體   English   中英

如何將 map 定義為常量 object 而不是每次調用時都會創建的方法

[英]How to define the map as a constant object instead of a method which will be created every time when it is called

這是我用來填充 map 的方法,將來還會添加其他數據。

public class myClass{
  public Map populateMap(client: RedissonClient) {
   Map map = client.getMap("map");
   map.put(k1, v1);
   map.put(k2, v2);
   ...
   
   return map;
 }
}

The problem is, each time when I calling this method in my main function, it will re-create the same map content again and again, is there a way to define it as a constant map object, not in a method.

Map map = myClass.populateMap(client);
...

從您的問題來看,尚不清楚 map 應該屬於實例還是屬於 class。

要創建 class 常量 map,請使用Map::of

class MyClass {

    static final Map<String, String> MAP = Map.of("k1", "v1", "k2", "v2");

}

上述 map 是不可修改的 map :保證不會對 map 1進行任何修改。 如果你想把這個 map 的內容變成一個新的 map,為了給它添加額外的數據,只需使用

Map<String, String> newMap = new HashMap<>(MyClass.MAP);
newMap.put(...);

1好吧,也許通過反思是可能的。 但是對於反射適用:只有在您知道自己在做什么時才使用它。

如果你使用方法 static,你可以初始化一個 static map:

public class MyClass{
  public static Map<String, String> map = populateMap();

  private static Map<String, String> populateMap() {
   Map<String, String> map = new HashMap<>();
   map.put("k1", "v1");
   map.put("k2", "v2");
   ...
  
   return map;
 }
}

現在所有其他類都可以訪問填充的MyClass.map

實際上已經說過,使 map 成為全局常量,或者在 java 術語中: static 最終字段

public class myClass {
    private static final Map<String, String> MAP = new HashMap<>();
    static {
        MAP.put(k1, v1);
        MAP.put(k2, v2);
    }

或者因為 java 9 更容易完成(感謝@GhostCat):

    private static final Map<String, String> MAP =
        Map.of(k1, v1,
               k2, v2);

使用類型,如接口Map<Integer, Object> 並為創建選擇實施 class。

static {... }稱為static 初始化程序

您可以將其設置為如上所述的全局變量。

public final static Map<String, String> MAP = populateMap();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM