How to give the static value to HashMap?

若如初见. 提交于 2019-12-07 23:14:20

问题


I have HashMap like:

static HashMap<String,ArrayList<Media>> mediaListWithCategory=new HashMap<String,ArrayList<Media>>();

I have value like:

January:
   -Sunday
   -Monday
Februsry:
   -Saturday
   -Sunday
   -Thursday
March:
   -Monday
   -Tuesday
   -Wednesday

How can I statically assign these values when defining the hash map?


回答1:


You can populate it in a static block:

static {
   map.put("January", Arrays.asList(new Media("Sunday"), new Media("Monday")));
}

(You should prefer interface to concrete classes. define your type as Map<String, List<Media>>)




回答2:


Use a static block:

static {
  mediaListWithCategory.put(youKey, yourValue);
}



回答3:


A variant of this may be more succinct:

static HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>() {{
    put("January", new ArrayList<String>() {{
        add("Sunday");
        add("Monday");
      }});
    put("Februsry" /* sic. */, new ArrayList<String>() {{
        add("Saturday");
        add("Sunday");
        add("Thursday");
      }});
    put("March", new ArrayList<String>() {{
        add("Monday");
        add("Tuesday");
        add("Wednesday");
      }});
}};

See Double Brace Initialisation for discussion.



来源:https://stackoverflow.com/questions/8211784/how-to-give-the-static-value-to-hashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!