why do methods like list map setof or arraysaslist 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]

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top