我想创建一个用于测试的选项列表。起初,我这样做:

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

然后,我将代码重构如下:

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

有更好的方法吗?


当前回答

最简单的方法:可以使用此方法向任意类型的集合(如ArrayList和HashSet)添加多个元素

ArrayList<String> allViews = new ArrayList<String>();
Collections.addAll(allViews,"hello","world","abc","def","ghi");

其他回答

最好的方法是:

package main_package;

import java.util.ArrayList;


public class Stackkkk {
    public static void main(String[] args) {
        ArrayList<Object> list = new ArrayList<Object>();
        add(list, "1", "2", "3", "4", "5", "6");
        System.out.println("I added " + list.size() + " element in one line");
    }

    public static void add(ArrayList<Object> list,Object...objects){
        for(Object object:objects)
            list.add(object);
    }
}

只需创建一个可以包含任意多个元素的函数,并调用它将它们添加到一行中即可。

List<String> names = Arrays.asList("2","@2234","21","11");

集合文本并没有进入Java 8,但可以使用流API在一行中初始化列表:

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

如果您需要确保列表是ArrayList:

ArrayList<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toCollection(ArrayList::new));

有多种方法可以在一行中创建和初始化列表。

    //Using Double brace initialization
    List<String> list1 = new ArrayList<>() {{ add("A");  add("B"); }};
    
    //Immutable List
    List<String> list2 = List.of("A", "B");

    //Fixed size list. Can't add or remove element, though replacing the element is allowed.
    List<String> list3 = Arrays.asList("A", "B");

    //Modifiable list
    List<String> list4 = new ArrayList<>(Arrays.asList("A", "B"));

    //Using Java Stream
    List<String> list5 = Stream.of("A", "B").collect(Collectors.toList());

    //Thread safe List
    List<String> list6 = new CopyOnWriteArrayList<>(Arrays.asList("A", "B"));
public static <T> List<T> asList(T... a) {
    return new ArrayList<T>(a);
}

这是Arrays.asList的实现,因此您可以使用

ArrayList<String> arr = (ArrayList<String>) Arrays.asList("1", "2");