对照示例
public static void main(String[] args) {
final List<String> list = new ArrayList<>();
list.add("aa");
list.add("bb");
list.add("cc");
list.remove("cc");
System.out.println(list);
}
结果:
Stream.toList
public static void main(String[] args) {
String[] array = new String[]{"aa", "bb", "cc"};
final List<String> list = Stream.of(array).toList();
list.remove("cc");
System.out.println(list);
}
结果:
程序报错,怀疑Stream.toList()方法返回的是一个连内容都不可改变的List,有点类似List.of()方法生成的List,比如下面代码也会报和上面代码一样的错误:
public static void main(String[] args) {
final List<String> list = List.of("aa", "bb", "cc");
list.remove("cc");
System.out.println(list);
}
解决方案
public static void main(String[] args) {
String[] array = new String[]{"aa", "bb", "cc"};
final List<String> list = new ArrayList(Stream.of(array).toList());
// final List<String> list = new ArrayList(Arrays.asList(array));
list.remove("cc");
System.out.println(list);
}
结论:
使用List.of()和Stream.toList()生成的List的内容是不能发生变化的