How to create Immutable List in java?

后端 未结 7 1866
隐瞒了意图╮
隐瞒了意图╮ 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 02:00

    Use Collections.unmodifiableList(). You pass in your original ArrayList and it returns a list that throws an exception if you try to add, remove or shift elements. For example, use return Collections.unmodifiableList(beanList); instead of return beanList; at the end of getImmutableList(). main() will throw an exception. The Collections class has methods for all of the other common collection types besides List as well.

提交回复
热议问题