I get surprised with the Google results, when I was looking into “Why Java Still Sexy”. I don’t know why for devil sake many of its cool features buried and it’s never discussed. I never ever heard few of them in my life time. Love to understand and transform the unseen features of java to you guys. Starting with one of the cool Double Braze Initialization
Though it looks cool, I do not want to see anonymous class unless it’s necessary. This might let you into memory leak. Also I don’t see any benefits in using this approach except unit testing with JMOCK.
How you will do if someone asked to write a code to initialize the Hash map and put some values within that. This is how I will respond,
Map <Integer, String> nMap = new HashMap < Integer, String >();
numberMap.put(1, "One");
numberMap.put(2, "Two");
numberMap.put(3, "Three");
numberMap.put(4, "Four");
My knowledge is up to the above approach only. Won’t believe java has other ways to achieve the same. That’s Double Braze Initialization. It’s allows you to initialize any of your object in double brace syntax. Initially I was claiming this as syntax error. Following code does the same as above.
Map <Integer, String> nMap = new HashMap < Integer, String >() {{
put(1, "One");
put(2, "Two");
put(3, "Three");
put(4, "Four");
}};
Cool na!. So why you need a 2 braces here?
The first brace creates a new AnonymousInnerClass, and the second brace tells that this is an instance initializer block which runs when the anonymous inner class is instantiated. This initializing block is called an Instance Initializer, because it is declared within the instance scope of the class.
Since its creating an anonymous subclass, Double brace initialization is only applicable for non final class. Please don’t ask me the reason. Also the nice fact is this Initializer runs even before the constructor. Double brace initialization not limited only to collections. You can initialize any kind of objects. Here are some examples.
In GUI:
add(new JPanel() {{
setLayout(...);
setBorder(...);
add(new JLabel(...));
add(new JSpinner(...));
}});
In JMOCK unit test case:
context.checking(new Expectations() {{
oneOf (plan).name(); will(returnValue(getName));
oneOf (service).attribute(); will(returnValue(getAtt));
}});
0 comments:
Post a Comment