With Ruby on Rails gaining popularity more and more people post comments about how awkward coding in Java (or .NET for that matter) is. Someone tried to explain why Java is this bad by explaining how PHP and Ruby can instantiate a Map of string and value pairs (called array in PHP). The syntax to define a Map in Ruby would be:
{
"name" => "Tomas Salfischberger",
"phone" => "123456789",
"room" => "11b"
}
And for PHP:
array(
"name" => "Tomas Salfischberger",
"phone" => "123456789",
"room" => "11b"
)
Now the problem with a lot of these comments is that most Java-critics can’t actually write proper Java code. There is, for example, the following method to instantiate the same Map in Java:
new HashMap() {{
put("name", "Tomas Salfischberger");
put("phone", "123456789");
put("room", "11b");
}}
It is true that there is a bit more typing involved, but how many seconds does this actually cost you? And what if you look at the extra information we have provided? In Java we have actually expressed that we need a HashMap and not for example a TreeMap. That is not just more typing because Java programmers like typing, it’s actually valuable information.
Another one which might be useful (but more widely known I guess?) is this function to create a List using the Java 5 varargs feature:
Arrays.asList("value1", "value2", "something else")
These are both just simple tricks to make a programmer’s life easier, unfortunately a lot of people don’t know about them. Let’s hope the lost Ruby souls will some day find out about the simple tricks in other languages ![]()





[…] Tomas posted the article Creating a Map in “Ruby-style” in Java, I wanted to tell you a little more about the { } block notation, which is used in that article to […]
Great tips. Still, more typing means worse readability, not better. Clear code is concise and to the point. I’ll take the Ruby/Python/JavaScript style any day.