Initialization of an ArrayList in one line

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

    Like Tom said:

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

    But since you complained of wanting an ArrayList, you should firstly know that ArrayList is a subclass of List and you could simply add this line:

    ArrayList myPlaces = new ArrayList(places);
    

    Although, that might make you complain of 'performance'.

    In that case it doesn't make sense to me, why, since your list is predefined it wasn't defined as an array (since the size is known at time of initialisation). And if that's an option for you:

    String[] places = {"Buenos Aires", "Córdoba", "La Plata"};
    

    In case you don't care of the minor performance differences then you can also copy an array to an ArrayList very simply:

    ArrayList myPlaces = new ArrayList(Arrays.asList(places));
    

    Okay, but in future you need a bit more than just the place name, you need a country code too. Assuming this is still a predefined list which will never change during run-time, then it's fitting to use an enum set, which would require re-compilation if the list needed to be changed in the future.

    enum Places {BUENOS_AIRES, CORDOBA, LA_PLATA}
    

    would become:

    enum Places {
        BUENOS_AIRES("Buenos Aires",123),
        CORDOBA("Córdoba",456),
        LA_PLATA("La Plata",789);
    
        String name;
        int code;
        Places(String name, int code) {
          this.name=name;
          this.code=code;
        }
    }
    

    Enum's have a static values method that returns an array containing all of the values of the enum in the order they are declared, e.g.:

    for (Places p:Places.values()) {
        System.out.printf("The place %s has code %d%n",
                      p.name, p.code);
    }
    

    In that case I guess you wouldn't need your ArrayList.

    P.S. Randyaa demonstrated another nice way using the static utility method Collections.addAll.

提交回复
热议问题