简体   繁体   中英

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 :

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. 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 .

If you want to get a mutable list, you can instantiate an ArrayList with this immutable list as the parameter.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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