Initialization of an ArrayList in one line

后端 未结 30 2212
北恋
北恋 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 02:00

    It would be simpler if you were to just declare it as a List - does it have to be an ArrayList?

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

    Or if you have only one element:

    List places = Collections.singletonList("Buenos Aires");
    

    This would mean that places is immutable (trying to change it will cause an UnsupportedOperationException exception to be thrown).

    To make a mutable list that is a concrete ArrayList you can create an ArrayList from the immutable list:

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

提交回复
热议问题