Initialization of an ArrayList in one line

后端 未结 30 2230
北恋
北恋 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:40

    In Java 9 we can easily initialize an ArrayList in a single line:

    List places = List.of("Buenos Aires", "Córdoba", "La Plata");
    

    or

    List places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));
    

    This new approach of Java 9 has many advantages over the previous ones:

    1. Space Efficiency
    2. Immutability
    3. Thread Safe

    See this post for more details -> What is the difference between List.of and Arrays.asList?

提交回复
热议问题