Java 9 为列表引入了新的工厂方法,List.of
:
List<String> strings = List.of("first", "second");
上一个选项和新选项有什么区别?也就是说,这有什么区别:
Arrays.asList(1, 2, 3);
还有这个:
List.of(1, 2, 3);
最佳答案
Arrays.asList
返回一个可变列表,而 List.of
返回的列表是 immutable :
List<Integer> list = Arrays.asList(1, 2, null);
list.set(1, 10); // OK
List<Integer> list = List.of(1, 2, 3);
list.set(1, 10); // Fails with UnsupportedOperationException
Arrays.asList
允许空元素,而 List.of
不允许:
List<Integer> list = Arrays.asList(1, 2, null); // OK
List<Integer> list = List.of(1, 2, null); // Fails with NullPointerException
contains
与 null 的行为不同:
List<Integer> list = Arrays.asList(1, 2, 3);
list.contains(null); // Returns false
List<Integer> list = List.of(1, 2, 3);
list.contains(null); // Fails with NullPointerException
Arrays.asList
返回传递数组的 View ,因此对数组的更改也将反射(reflect)在列表中。对于 List.of
这是不正确的:
Integer[] array = {1,2,3};
List<Integer> list = Arrays.asList(array);
array[1] = 10;
System.out.println(list); // Prints [1, 10, 3]
Integer[] array = {1,2,3};
List<Integer> list = List.of(array);
array[1] = 10;
System.out.println(list); // Prints [1, 2, 3]
关于java - List.of 和 Arrays.asList 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46579074/