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:


Comments:
That's a nice trick!

I too despise how verbose Java code can be.

I wonder though what performance cost there is by doing it the way you suggest...
 
This comment has been removed by a blog administrator.
 
This comment has been removed by a blog administrator.
 
This comment has been removed by a blog administrator.
 
This comment has been removed by a blog administrator.
 
I think, it would skip compile time checks and will never throw exceptions.
For example, what happens if the memory is full after the first put?
 
@Monty, it would throw an exception as always. This trick doesn't change compile or run-time dependencies any differently than had it not been inlined. The put's are still validated against the Map's signature and must still match.
 
This is not very helpful 'cause it doesn't reduce the number of lines to be written and it degrades the performance (very slightly, alright) due to the use of anonymous classes. Not helpful at all for me. It would be nice if the HashMap constructor could accept a matrix of Nx2 where N is the number of map entries, something like:

new HashMap<>({[key1, value1], [key2, value2], ...};
 
Post a Comment



<< Home

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