代码之家  ›  专栏  ›  技术社区  ›  Abdullah Jibaly

为什么Java集合有0个或1个元素,而不是更多的元素?

  •  2
  • Abdullah Jibaly  · 技术社区  · 14 年前

    如果我想要一个空的地图或一个元素的地图,Java集合有一个方法。为什么一个以上的元素没有方法?创建包含两个元素的静态最终映射的最佳方法是什么?我知道我可以做如下的事情:

    private static final Map<String, String> MAP = new HashMap<String, String>() {
        { put("a", "b"); put("c", "d"); }
    };
    

    但后来Eclipse抱怨说它的序列号为

    5 回复  |  直到 14 年前
        1
  •  16
  •   ColinD    14 年前

    Collections Map

    Guava Immutable* ImmutableMap

    private static final ImmutableMap<String, String> MAP = ImmutableMap.of(
        "a", "b",
        "c", "d");
    

    private static final ImmutableMap<String, String> MAP = 
        ImmutableMap.<String, String>builder()
          .put("a", "b")
          .put("b", "c")
          ...
          .put("y", "z")
          .build();
    

    private static final Map<String, String> MAP;
    
    static {
      Map<String, String> temp = new HashMap<String, String>();
      temp.put("a", "b");
      temp.put("b", "c");
      MAP = Collections.unmodifiableMap(temp);
    }
    
        2
  •  2
  •   Jay Sheridan    14 年前

    MAP

    static { 
       MAP.put("a", "b"); 
       MAP.put("c", "d");
    }
    

    This article

    private static final Map<String, String> MAP;
    static {
        Map<String, String> tempMap = new HashMap<String, String>();
        tempMap.put("a", "b");
        tempMap.put("c", "d");
        MAP = Collections.unmodifiableMap(tempMap);
    }
    
        3
  •  1
  •   thejh    14 年前

    private static final Map<String, String> Map = buildMap();
    
    private static Map<String, String> buildMap() {
      Map<String, String> map = new HashMap<String, String>();
      map.put("a", "b");
      map.put("c", "d");
      return Collections.unmodifiableMap(map);
    }
    
        4
  •  0
  •   Mark Storer    14 年前

    private static final Map<String, String> Map = buildMap();
    
    private static Map<String, String> buildMap() {
      Map<String, String> map = new HashMap<String, String>();
      map.put("a", "b");
      map.put("c", "d");
      return map;
    }
    

        5
  •  0
  •   user207421    14 年前