Efficiency of Java “Double Brace Initialization”?

前端 未结 15 2130
清歌不尽
清歌不尽 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:10

    Efficiency aside, I rarely find myself wishing for declarative collection creation outside of unit tests. I do believe that the double brace syntax is very readable.

    Another way to achieve the declarative construction of lists specifically is to use Arrays.asList(T ...) like so:

    List aList = Arrays.asList("vanilla", "strawberry", "chocolate");
    

    The limitation of this approach is of course that you cannot control the specific type of list to be generated.

提交回复
热议问题