This expression creates an instance of an anonymous class which extends HashMap. The anonymous class includes an instance initializer block which contains the "put" calls. Are you familiar with either of these things yet? An anonymous inner class is a way of defining a subclass without giving it a name. An instance initializer block is basically a way to add code to all the constructors in a class. This code is really equivalent to
In any case, depending on who you ask, this is a cute hack, or a crime against humanity. It's not a very common idiom, and I hope it doesn't become moreso.
[ Edit: DRAT! Beaten! ] [ October 10, 2008: Message edited by: Ernest Friedman-Hill ]
Rene Wooller wrote:Hi All,
A lot of people are saying how they wouldn't do this. Would you mind listing a few alternatives?
Personally, if I wanted to expose this map as a public field, I would want to ensure that not only is the reference final, but the object itself is immutable. We don't want anyone calling put() or remove(0 on the map once it has been constructed. Traditionally this could be done like this:
Rene Wooller wrote:All I can think of at the moment is a declarative approach, using a properties file or xml or somesuch, in which case, the benefit would be ease or change.
Yeah, something like that could certainly be useful. If you want to load key-value pairs from some other source, I would put that loading code inside the initializeMap() method. You can do whatever you want there. If it needs more careful testing, it's easy to make the method package-private or some other access. The reason I often prefer a named method to a static initializer is that it's easier to test a named method.
Rene Wooller wrote:But this would a bit of hassle. I think the example given would be faster to code, and I personally don't find it hard to read at all.
Well, it's an unusual syntax that has just started to appear recently. A lot of people don't like it simply because they don't recognize it - or because they figure many other people will not recognize it. Which I think is a fair point. If I'm going to bring in something new that people might not be familiar with, I'd rather it be Guava, because that makes the code look much nicer and gives many other useful methods as well.