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

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"));

有更好的方法吗?


当前回答

最简单的方法是:

Double array[] = { 1.0, 2.0, 3.0};
List<Double> list = Arrays.asList(array);

其他回答

有趣的是,没有列出带有另一个重载Stream::collect方法的一行

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

尝试使用以下代码行:

Collections.singletonList(provider)

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

    //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"));

最简单的方法是:

Double array[] = { 1.0, 2.0, 3.0};
List<Double> list = Arrays.asList(array);

实际上,可以在一行中完成:

Arrays.asList(new MyClass[] {new MyClass("arg1"), new MyClass("arg2")})