Efficiency of Java “Double Brace Initialization”?

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

    I second Nat's answer, except I would use a loop instead of creating and immediately tossing the implicit List from asList(elements):

    static public Set setOf(T ... elements) {
        Set set=new HashSet(elements.size());
        for(T elm: elements) { set.add(elm); }
        return set;
        }
    

提交回复
热议问题