小编Ted*_*sai的帖子

为什么 Collectors.toList() 不能保证可变性

toList() 的实现明确返回一个 ArrayList,它确实保证了可变性:

public static <T>
Collector<T, ?, List<T>> toList() {
    return new CollectorImpl<>(ArrayList::new, List::add,
                               (left, right) -> { left.addAll(right); return left; },
                               CH_ID);
}
Run Code Online (Sandbox Code Playgroud)

但是 toList 的 JavaDoc 是这样的:

/**
 * Returns a {@code Collector} that accumulates the input elements into a
 * new {@code List}. There are no guarantees on the type, mutability,
 * serializability, or thread-safety of the {@code List} returned; if more
 * control over the returned {@code List} is required, use {@link #toCollection(Supplier)}.
 *
 * …
Run Code Online (Sandbox Code Playgroud)

java collections java-8 java-stream collectors

2
推荐指数
1
解决办法
199
查看次数

标签 统计

collections ×1

collectors ×1

java ×1

java-8 ×1

java-stream ×1