List.of和Arrays.asList有什么区别?
Java 9引入了新的Collection Factory方法, List.of
:
Java 9 introduced new Collection Factory methods, List.of
:
List<String> strings = List.of("first", "second");
那么,之前和新选项之间有什么区别?也就是说,它之间有什么区别:
So, what's the difference between the previous and the new options? That is, what's the difference between this:
Arrays.asList(1, 2, 3);
这个:
List.of(1, 2, 3);
Arrays.asList
返回一个可变列表,而 List.of
返回的列表是不可变的:
Arrays.asList
returns a mutable list while the list returned by List.of
is 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
Arrays.asList
允许null元素 List.of
不:
Arrays.asList
allows null elements while List.of
doesn't:
List<Integer> list = Arrays.asList(1, 2, null); // OK
List<Integer> list = List.of(1, 2, null); // Fails with a NullPointerException
包含
方法行为与空值不同:
contains
method behaves differently with nulls:
List<Integer> list = Arrays.asList(1, 2, 3);
list.contains(null); // Return false
List<Integer> list = List.of(1, 2, 3);
list.contains(null); // Throws NullPointerException
Arrays.asList
返回传递数组的视图,因此对数组的更改也将反映在列表中。对于 List.of
,这不是真的:
Arrays.asList
returns a view of the passed array, so the changes to the array will be reflected in the list too. For List.of
this is not true:
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]