Use of Java's Collections.singletonList()?

前端 未结 6 866
無奈伤痛
無奈伤痛 2021-01-29 18:58

What is the use of Collections.singletonList() in Java? I understand that it returns a list with one element. Why would I want to have a separate method to do that?

6条回答
  •  孤街浪徒
    2021-01-29 19:23

    To answer your immutable question:

    Collections.singletonList will create an immutable List. An immutable List (also referred to as an unmodifiable List) cannot have it's contents changed. The methods to add or remove items will throw exceptions if you try to alter the contents.

    A singleton List contains only that item and cannot be altered.

提交回复
热议问题