【问题标题】:How to manually fill out a HashMap?如何手动填写HashMap?
【发布时间】:2015-11-30 05:15:12
【问题描述】:

如何手动填写下面的HashMap?

public static final HashMap<String,int[]> AGE_GROUPS = {"18-24",{18,24},
                                                        "25-29",{25,29},
                                                        "30-39",{30,39},
                                                        "40-49",{40,49},
                                                        "50-59",{50,59},
                                                        "60-69",{60,69},
                                                        "70-79",{70,79},
                                                        "80+",{80,120}};

【问题讨论】:

标签: java hashmap


【解决方案1】:

这是我将使用辅助方法的地方

public static Map<String, int[]> rangeMap(int... fromTo) {
    Map<String,int[]> map = new LinkedHashMap<>();
    for (int i = 0; i < fromTo.length; i += 2) {
        String key = fromTo[i] + (fromTo[i+1] > 100 ? "+" : "-"+fromTo[i+1]);
        map.put(key, new int[] { fromTo[i], fromTo[i+1]));
    return Collections.unmodifiableMap(map);
}

public static final Map<String,int[]> AGE_GROUPS = rangeMap(
    0, 17, 
   18, 24, 
   25, 29,
   30, 39,
   40, 49,
   50, 59,
   60, 69,
   70, 79,
   80, 120);

【讨论】:

  • 不错,但不会为最终映射生成"80+" 字符串。
  • @Andreas 修复了它。虽然如果你超过 120 岁,你就不会超过 80 岁
  • 我同意,但到目前为止,只有一个人这么老。我会选择 999 或未定义的,即 "80+" 映射的 int[1] 值,但这是 OP 的选择。
【解决方案2】:

这称为静态初始化。

 private static final Map<Integer, String> myMap;
    static {
        Map<Integer, String> aMap = ....;
        aMap.put(1, "one");
        aMap.put(2, "two");
        myMap = Collections.unmodifiableMap(aMap);
    }

在你的情况下;

public static final Map<String, int[]> AGE_GROUPS;
    static{
        Map<String, int[]> otherMap = new HashMap<String, int[]>();
        otherMap.put( "10-20", new int[]{ 10, 11 } );
        otherMap.put( "20-30", new int[]{ 20, 21 } );

        AGE_GROUPS = Collections.unmodifiableMap( otherMap );

    }

【讨论】:

  • 我的意思是不用这条线; ` myMap = Collections.unmodifiableMap(aMap);` 他可以使用自己的地图。但是还是编辑了我的答案,谢谢。
  • 你能举一个我的年龄组的例子吗(HashMap?如何静态初始化它?
  • 知道了! HashMap aMap = new HashMap(); aMap.put("18-24", new int[]{18,24});
猜你喜欢
  • 1970-01-01
  • 2010-11-12
  • 2019-12-01
  • 1970-01-01
  • 2021-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-16
相关资源
最近更新 更多