How to declare an ArrayList with values?

This question already has an answer here:

  • Initialization of an ArrayList in one line 32 answers

  • You can create a new object using the constructor that accepts a Collection :

    List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));
    

    Tip: The docs contains very useful information that usually contains the answer you're looking for. For example, here are the constructors of the ArrayList class:

  • ArrayList()

    Constructs an empty list with an initial capacity of ten.

  • ArrayList(Collection<? extends E> c) (*)

    Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

  • ArrayList(int initialCapacity)

    Constructs an empty list with the specified initial capacity.


  • Java 8 solution using Stream :

    Stream.of("xyz", "abc").collect(Collectors.toList());
    

    你可以这样做:

    List<String> temp = new ArrayList<String>(Arrays.asList("1", "12"));
    

    Use:

    List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));
    

    If you don't want to add new elements to the list later, you can also use (Arrays.asList returns a fixed-size list):

    List<String> x = Arrays.asList("xyz", "abc");
    

    Note: you can also use a static import if you like, then it looks like this:

    import static java.util.Arrays.asList;
    

    ...

    List<String> x = new ArrayList<>(asList("xyz", "abc"));
    

    or

    List<String> x = asList("xyz", "abc");
    
    链接地址: http://www.djcxy.com/p/27706.html

    上一篇: 我如何初始化一个集合并在同一行添加数据?

    下一篇: 如何声明一个ArrayList的值?