问题
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