A bet you don’t know about these in Java!

Double Brace Initialization

Probably a lot of time you whish to initialize a collection in Java with default values at construction time, but without doing the sequence stuff like this one (too many statements):

How to do it?

Using a static method asList (probably you know about this one!)

Functional style, fewer lines, very precise, and clear!

Using Double Brace Initialization

If you think a little about it you will see nothing knew, but may surprise you this way of initialization!

Is this a hidden feature in Java? No!

If you know something about anonymous classes and anonymous constructors, nothing here is new!

The first “{“ is creating an anonymous subclass of ArrayList, and the second “{“ is used to create an anonymous constructor.

Let me put the code in another way:

More clear now?

Java has some hidden gems that they deserve to be found!

 

del.icio.us Tags: ,
Technorati Tags: ,
43 Things Tags: ,

Bad Behavior has blocked 110 access attempts in the last 7 days.

Hyper Smash