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 群随时交流、讨论,也非常感谢同学的支持!
112019-02-07
相似问题