Initialization of an ArrayList in one line

后端 未结 30 2857
北恋
北恋 2020-11-22 01:10

I wanted to create a list of options for testing purposes. At first, I did this:

ArrayList places = new ArrayList();
places.add(\         


        
30条回答
  •  我在风中等你
    2020-11-22 01:41

    Here is code by AbacusUtil

    // ArrayList
    List list = N.asList("Buenos Aires", "Córdoba", "La Plata");
    // HashSet
    Set set = N.asSet("Buenos Aires", "Córdoba", "La Plata");
    // HashMap
    Map map = N.asMap("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3);
    
    // Or for Immutable List/Set/Map
    ImmutableList.of("Buenos Aires", "Córdoba", "La Plata");
    ImmutableSet.of("Buenos Aires", "Córdoba", "La Plata");
    ImmutableSet.of("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3);
    
    // The most efficient way, which is similar with Arrays.asList(...) in JDK. 
    // but returns a flexible-size list backed by the specified array.
    List set = Array.asList("Buenos Aires", "Córdoba", "La Plata");
    

    Declaration: I'm the developer of AbacusUtil.

提交回复
热议问题