Initialization of an ArrayList in one line

后端 未结 30 2694
北恋
北恋 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条回答
  •  Happy的楠姐
    2020-11-22 02:00

    Java 9 has the following method to create an immutable list:

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

    which is easily adapted to create a mutable list, if required:

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

    Similar methods are available for Set and Map.

提交回复
热议问题