Use of Java's Collections.singletonList()?

前端 未结 6 868
無奈伤痛
無奈伤痛 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:21

    singletonList can hold instance of any object. Object state can be modify.

    List list = new ArrayList();
    list.add('X');
    list.add('Y');
    System.out.println("Initial list: "+ list);
    List> list2 = Collections.singletonList(list);
    list.add('Z');
    System.out.println(list);
    System.out.println(list2);
    

    We can not define unmodifiableList like above.

提交回复
热议问题