0

Came across this peculiar way of initializing Java maps inline.

The following code seems to be extending the Hashmap class using an anonymous class and is then using the (non static) initializer block.

Map<String, String> aMap = new HashMap<String, String>()
{{
   put("gloves", "hand");
   put("hat", "head");
   put("shoes", "feet");
   put("scarf", "neck");
}};

What are the performance implication of using the above code to initialize hashmaps inline?

I have not seen this being used very often. Is it considered to be a good java practice ?

davison
  • 335
  • 1
  • 3
  • 16
  • Why don't you write a test application to initialise some test maps and see for yourself? – ZeroOne Sep 30 '14 at 13:37
  • 1
    The first issue that comes to my mind is that anonymous classes produce an _extra_ .class file after being compiled. About performance... if it were to be used in a static initialization (=only once in a JVM), I don't think performance would be a big deal. Not sure about being a good practice, since an anonymous class is not reusable and extending a class is supposed to be aimed to change its behaviour. – Little Santi Sep 30 '14 at 13:45
  • 3
    @ZeroOne Properly benchmarking JIT'd code is extremely difficult. Before resorting to benchmarks it is essential to understand *why* something like this should be expected to be faster or slower. – Boann Sep 30 '14 at 13:47

3 Answers3

1

@davison this question has been discussed many times on SO. Even if the data structure is not the same (Set, HashSet) instead of (Map, HashMap) I personally think the following is the best discussion and should clarify all your doubts: Efficiency of Java "Double Brace Initialization"?

Community
  • 1
  • 1
Alboz
  • 1,833
  • 20
  • 29
0

This is not a good practise, because it creates a new anonymous inner class which the JVM has to use more memory to keep track of. Other than that, it's mostly harmless.

A better way of writing this code would be to use an initialisation block:

Map<String, String> aMap = new HashMap<String, String>();
{
    aMap.put("gloves", "hand");
    aMap.put("hat", "head");
    aMap.put("shoes", "feet");
    aMap.put("scarf", "neck");
}
Stuart Caie
  • 2,803
  • 14
  • 15
0

What are the performance implication of using the above code to initialize hashmaps inline?

Almost none. The first time you do it there is extra class loading which is unlikely to be important unless you care about the number of classes you use.

I have not seen this being used very often. Is it considered to be a good java practice ?

I would say it is good practice if it makes the code clearer, esp in unit tests.

Where it is bad practice is if this collection gets put in a thread local as this can prevent the module unloading.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130