A weird Java trick for populating collections that you should never use!

A lot of people (myself included) complain about how verbose Java is.  This is especially true when it comes to populating collections from the Java Collection API.  Here’s what you typically see:

It’s frustrating that this is so verbose.  Wouldn’t it be better if you could do this common task in a concise way?  Well… there is actually a trick you can use in Java to do this.  It looks like this:

This has exactly the same result, but you should never do this:  This is difficult to read and most Java Engineers don’t even know how this works.  Then why did I decide to write an article about this if it’s a “worst practice”?  Well, it can be fun to know about tricks in Java that others don’t.  But more importantly, there is something to learn here.  What is this doing?  How does it work?  We are going to learn that and at the very end I’ll show you what code you should be using instead that’s the best of both worlds.

Continue reading