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:
1 2 3 4 |
List<String> ugh = new ArrayList<String>(); ugh.add("a"); ugh.add("b"); ugh.add("c"); |
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:
1 |
List<String> wat = new ArrayList<String>() {{ add("a"); add("b"); add("c"); }}; |
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.