In Hidden Features of Java the top answer mentions Double Brace Initialization, with a very enticing syntax:
Set flavors = new HashSet
There's no legitimate reason to use this "trick". Guava provides nice immutable collections that include both static factories and builders, allowing you to populate your collection where it's declared in a clean, readable, and safe syntax.
The example in the question becomes:
Set flavors = ImmutableSet.of(
"vanilla", "strawberry", "chocolate", "butter pecan");
Not only is this shorter and easier to read, but it avoids the numerous issues with the double-braced pattern described in other answers. Sure, it performs similarly to a directly-constructed HashMap
, but it's dangerous and error-prone, and there are better options.
Any time you find yourself considering double-braced initialization you should re-examine your APIs or introduce new ones to properly address the issue, rather than take advantage of syntactic tricks.
Error-Prone now flags this anti-pattern.