Initialization of an ArrayList in one line

后端 未结 30 2204
北恋
北恋 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:57
    Collections.singletonList(messageBody)
    

    If you'd need to have a list of one item!

    Collections is from java.util package.

    0 讨论(0)
  • 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<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
    

    Or if you have only one element:

    List<String> 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<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
    
    0 讨论(0)
  • 2020-11-22 02:00

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

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

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

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

    Similar methods are available for Set and Map.

    0 讨论(0)
  • 2020-11-22 02:00

    For me Arrays.asList() is the best and convenient one. I always like to initialize that way. If you are a beginner into Java Collections then I would like you to refer ArrayList initialization

    0 讨论(0)
  • 2020-11-22 02:02

    You could create a factory method:

    public static ArrayList<String> createArrayList(String ... elements) {
      ArrayList<String> list = new ArrayList<String>();
      for (String element : elements) {
        list.add(element);
      }
      return list;
    }
    
    ....
    
    ArrayList<String> places = createArrayList(
      "São Paulo", "Rio de Janeiro", "Brasília");
    

    But it's not much better than your first refactoring.

    For greater flexibility, it can be generic:

    public static <T> ArrayList<T> createArrayList(T ... elements) {
      ArrayList<T> list = new ArrayList<T>();
      for (T element : elements) {
        list.add(element);
      }
      return list;
    }
    
    0 讨论(0)
  • 2020-11-22 02:02

    About the most compact way to do this is:

    Double array[] = { 1.0, 2.0, 3.0};
    List<Double> list = Arrays.asList(array);
    
    0 讨论(0)
提交回复
热议问题