Collections.singleton()就返回一个Set, 为何还要包一个new HashSet(Collections.singleton(..))

来源:8-10 【试试举一反三】全量索引加载的实现(1)

慕雪7212599

2019-02-04

写回答

1回答

张勤一

2019-02-04

同学你好:

    Collections.singleton 返回的是一个不可变对象(不可变 Set),但是,如果后面需要修改这个 Set 都需要再去包一层,即看到的 new HashSet。可以查看源码如下:

/**
 * Returns an immutable set containing only the specified object.
 * The returned set is serializable.
 *
 * @param  <T> the class of the objects in the set
 * @param o the sole object to be stored in the returned set.
 * @return an immutable set containing only the specified object.
 */
public static <T> Set<T> singleton(T o) {
    return new SingletonSet<>(o);
}


    欢迎来 QQ 群随时交流、讨论,也非常感谢同学的支持! 

1
1
慕雪7212599
老师, 既然还要修改, 为什么还要用singleton呢, 希望早点完整带项目, 查看代码就方便多了
2019-02-07
共1条回复

Spring Cloud微服务架构 设计实现广告系统

广告营销系统,未来大中型企业的标配

2136 学习 · 927 问题

查看课程