How to create Immutable List in java?

后端 未结 7 1852
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 01:16

I need to convert mutable list object to immutable list. What is the possible way in java?

public void action() {
    List mutableList =          


        
7条回答
  •  悲&欢浪女
    2020-12-29 01:53

    From Java 10 on, List.copyOf(Collection) can be used to return an unmodifiable list from the given collection. From source code of List.copyOf method:

    • if the given collection is an unmodifiable List, List.copyOf() will not create a copy.

    • if the given collection is mutable and modified, the returned list will not reflect such modifications. Meaning they are independent.

提交回复
热议问题