简体   繁体   English

为什么像 List/Map/Set.of(...) 或 Arrays.asList(...) 这样的方法返回一个不可变的列表?

[英]Why do methods like List/Map/Set.of(...) or Arrays.asList(...) return an immutable list?

返回不可变列表而不是可变列表的原因是什么?

Performance表现

Given below is the excerpt from Oracle JDK 9 Documentation :以下是Oracle JDK 9 文档的摘录:

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 are static factory methods which provide a convenient way to create immutable lists. List#of是静态工厂方法,它提供了一种创建不可变列表的便捷方法 In other words, it's a convenience method to create immutable lists.换句话说,这是创建不可变列表的便捷方法 Prior to Java-9, this was possible through separate APIs like Collections#unmodifiableList .在 Java-9 之前,这可以通过单独的 API 实现,例如Collections#unmodifiableList

If you want to get a mutable list, you can instantiate an ArrayList with this immutable list as the parameter.如果你想得到一个可变列表,你可以用这个不可变列表作为参数实例化一个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);
    }
}

Output:输出:

[A, B, C, D]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM