Efficiency of Java “Double Brace Initialization”?

前端 未结 15 2127
清歌不尽
清歌不尽 2020-11-21 15:35

In Hidden Features of Java the top answer mentions Double Brace Initialization, with a very enticing syntax:

Set flavors = new HashSet         


        
15条回答
  •  情歌与酒
    2020-11-21 16:14

    Double-brace initialization is an unnecessary hack that can introduce memory leaks and other issues

    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.

提交回复
热议问题