问题

Java中Collections.singletonList()的用途是什么?我知道它返回一个包含一个元素的列表。为什么我想要一个单独的方法来做到这一点?不变性如何在这里发挥作用?

这个方法有没有特别有用的用例,而不仅仅是一个方便的方法?


#1 热门回答(115 赞)

javadoc这个:

"返回仅包含指定对象的不可变列表。返回的列表是可序列化的。"

你问:

为什么我想要一个单独的方法来做到这一点?

为方便起见......为了节省你必须编写一系列语句:

  • 创建一个空列表对象
  • 添加一个元素,和
  • 用不可变的包装器包装它。

此方法是否有任何特殊有用的用例,而不仅仅是一种方便的方法?

显然,有一些用例可以方便地使用singletonList方法。但我不知道你会如何(客观地)区分普通用例和"特别有用"用例......


#2 热门回答(18 赞)

这是单例方法中的oneview

我发现这些各种"单例"方法对于将单个值传递给需要该值集合的API非常有用。当然,当处理传入值的代码不需要添加到集合时,这种方法效果最好。


#3 热门回答(7 赞)

@param  the sole object to be stored in the returned list.
@return an immutable list containing only the specified object.

import java.util.*;

public class HelloWorld {
    public static void main(String args[]) {
        // create an array of string objs
        String initList[] = { "One", "Two", "Four", "One",};

        // create one list
        List list = new ArrayList(Arrays.asList(initList));

        System.out.println("List value before: "+list);

        // create singleton list
        list = Collections.singletonList("OnlyOneElement");
        list.add("five"); //throws UnsupportedOperationException
        System.out.println("List value after: "+list);
    }
}

当代码需要只读列表时使用它,但你只想在其中传递一个元素.singletonListis(thread-)安全且快速。


原文链接