为什么像 List/Map/Set.of(...) 或 Arrays.asList(...) return 这样的方法是一个不可变列表?
Why do methods like List/Map/Set.of(...) or Arrays.asList(...) return an immutable list?
返回不可变列表而不是可变列表背后的原因是什么?
性能
以下摘录自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
.
如果你想得到一个可变列表,你可以用这个不可变列表作为参数实例化一个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]
返回不可变列表而不是可变列表背后的原因是什么?
性能
以下摘录自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
.
如果你想得到一个可变列表,你可以用这个不可变列表作为参数实例化一个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]