Arrays.asList返回一个可变列表,而List.of返回的列表是不可变的:
List list = Arrays.asList(1, 2, null);
list.set(1, 10); // OK
List list = List.of(1, 2, 3);
list.set(1, 10); // Fails
Arrays.asList允许null元素,而List.of不允许:
List list = Arrays.asList(1, 2, null); // OK
List list = List.of(1, 2, null); // Fails with a NullPointerException
contains方法与null的行为不同:
List list = Arrays.asList(1, 2, 3);
list.contains(null); // Return false
List list = List.of(1, 2, 3);
list.contains(null); // Throws NullPointerException
Arrays.asList返回传递的数组的视图,因此对数组的更改也将反映在列表中.对于List.of,这不是真的:
Integer[] array = {1,2,3};
List list = Arrays.asList(array);
array[1] = 10;
System.out.println(list); // Prints [1, 10, 3]
Integer[] array = {1,2,3};
List list = List.of(array);
array[1] = 10;
System.out.println(list); // Prints [1, 2, 3]