Efficiency of Java “Double Brace Initialization”?

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

    To create sets you can use a varargs factory method instead of double-brace initialisation:

    public static Set setOf(T ... elements) {
        return new HashSet(Arrays.asList(elements));
    }
    

    The Google Collections library has lots of convenience methods like this, as well as loads of other useful functionality.

    As for the idiom's obscurity, I encounter it and use it in production code all the time. I'd be more concerned about programmers who get confused by the idiom being allowed to write production code.

提交回复
热议问题