我想创建一个用于测试的选项列表。起初,我这样做:
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"));
有更好的方法吗?
有多种方法可以在一行中创建和初始化列表。
//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"));
集合文本并没有进入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));