Why collection literals?

前端 未结 11 877
无人及你
无人及你 2020-12-29 04:09

From the various online articles on Java 7 I have come to know that Java 7 will be having collection literals1 like the following:

List

        
11条回答
  •  盖世英雄少女心
    2020-12-29 04:50

    Another thing to note is that for lists this is very easy using var args, but have a little think about how you'd do it for a map. There is no way to supply pairs of arguments to a var args method, unless you introduce an extra Map.Entry object or something like that.

    So using existing syntax you'd end up with

    Map map = HashMap.of( new Entry( "key1", "value1" ), 
                                         new Entry( "key2", "value2" ) );
    

    which would get very tiring very quickly.

    Even if you go down the path of using a builder pattern (as we do) then it's pretty ugly

    Map map = CollectionUtil.map()
                                            .put( "key1", "value1" )
                                            .put( "key2", "value2" )
                                            .map();
    

提交回复
热议问题