Search code examples
javalistjava-9

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


What is the reasoning behind returning a immutable list instead of a mutable list?


Solution

  • 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]