Efficiency of Java “Double Brace Initialization”?

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

    1. This will call add() for each member. If you can find a more efficient way to put items into a hash set, then use that. Note that the inner class will likely generate garbage, if you're sensitive about that.

    2. It seems to me as if the context is the object returned by new, which is the HashSet.

    3. If you need to ask... More likely: will the people who come after you know this or not? Is it easy to understand and explain? If you can answer "yes" to both, feel free to use it.

提交回复
热议问题