返回不可变列表而不是可变列表背后的原因是什么?
最佳答案
性能
下面是 Oracle JDK 9 Documentation 的摘录:
For optimal performance, the immutable collections store a data set that never changes. However, you may be able to take advantage of the performance and space-saving benefits even if your data is subject to change. These collections may provide better performance than the mutable collections, even if your data changes occasionally.
List#of
是静态工厂方法,它提供了一种便捷的方式来创建不可变列表。换句话说,它是创建不可变列表的便捷方法。在 Java-9 之前,这可以通过单独的 API 实现,例如 Collections#unmodifiableList
.
如果你想获取一个可变列表,可以用这个不可变列表作为参数实例化一个ArrayList
。
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> mutableList = new ArrayList<>(List.of("A", "B", "C"));
mutableList.add("D");
System.out.println(mutableList);
}
}
输出:
[A, B, C, D]
关于java - 为什么像 List/Map/Set.of(...) 或 Arrays.asList(...) 这样的方法会返回不可变列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64636934/