Efficiency of Java “Double Brace Initialization”?

前端 未结 15 2394
清歌不尽
清歌不尽 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条回答
  •  萌比男神i
    2020-11-21 16:23

    Mario Gleichman describes how to use Java 1.5 generic functions to simulate Scala List literals, though sadly you wind up with immutable Lists.

    He defines this class:

    package literal;
    
    public class collection {
        public static  List List(T...elems){
            return Arrays.asList( elems );
        }
    }
    

    and uses it thusly:

    import static literal.collection.List;
    import static system.io.*;
    
    public class CollectionDemo {
        public void demoList(){
            List slist = List( "a", "b", "c" );
            List iList = List( 1, 2, 3 );
            for( String elem : List( "a", "java", "list" ) )
                System.out.println( elem );
        }
    }
    

    Google Collections, now part of Guava supports a similar idea for list construction. In this interview, Jared Levy says:

    [...] the most heavily-used features, which appear in almost every Java class I write, are static methods that reduce the number of repetitive keystrokes in your Java code. It's so convenient being able to enter commands like the following:

    Map = Maps.newHashMap();

    List animals = Lists.immutableList("cat", "dog", "horse");

    7/10/2014: If only it could be as simple as Python's:

    animals = ['cat', 'dog', 'horse']

    2/21/2020: In Java 11 you can now say:

    animals = List.of(“cat”, “dog”, “horse”)

提交回复
热议问题