Friday, April 10, 2009

 

Initializing Java Maps Inline

Java is by no means a succinct language. For simple operations, the programmer is expected to punch in a hundred keys; but there are a few little shortcuts that can help (and of course Eclipse is always there to help). One such trick is inline initialization of Map which I stumbled across recently and found to be very interesting.

We are all used to using the following code to initialize a map -


Map<String, String> map = new HashMap<String, String>();
map.put("Harry", "Potter");
map.put("Ron", "Weasley");
map.put("Hermione", "Granger");

The problem with this code is it is four different statements. Using a small static initialization trick, you can make it to be a single statement as follows:


Map<String, String> map = new HashMap<String, String>() {{
   put("Harry", "Potter");
   put("Ron", "Weasley");
   put("Hermione", "Granger");
}};

All we are doing here is sub-classing the HashMap class to an anonymous class, and then using the non-static initialization block to call the put() method three times.

PS - I have not updated this blog in a while, as I have been rather busy lately. From now on I will try to find some time, to at least write one post per month.

Labels:


This page is powered by Blogger. Isn't yours?