Initializing Java Maps
Last week as I was performing a code review when I stumbled upon a little gem. I use Java almost everyday but I had never seen a concise way to initialize a Map in Java. For arrays I do:
String[] allowed = new String[] {"text/html", "text/json"};
But what about Maps?
import java.util.*;
public class Router {
public static final Map<String, Handler> routes;
static {
Map<String, Handler> map = new HashMap<String, Handler>();
map.put("/account", new AccountHandler());
map.put("/feed", new FeedHandler());
map.put("/opml", new OpmlHandler());
routes = Collections.unmodifiableMap(map);
}
}
So did you know you could do this?
public static final Map<String , Handler> routes =
new HashMap<String , Handler>() {{
put("/account", new AccountHandler());
put("/feed", new FeedHandler());
put("/opml", new OpmlHandler());
}};
I did not. I looked around the web looking for the precise answer and found very few examples of this syntax. I found a post by code_poet referring to the feature as “initializing block” and describing it as creating a subclass and initializing the map upon construction. I even skimmed the Java Specification Language looking for more details, but no luck. Any better explanations?
About this entry
You’re currently reading “Initializing Java Maps,” an entry on Elias Torres
- Published:
- 03.08.08 / 2pm
- Category:
- Technology
12 Comments
Jump to comment form | comments rss [?] | trackback uri [?]