我有一个不可变的集合(转换为 Set<Integer>
),它可能包含许多元素。我需要一个包含该集合中的元素和一个附加元素的集合。我有一些笨拙的代码来复制集合,然后附加元素,但我正在寻找使事情尽可能高效的正确方法。
我有 Guava 可用,但我不需要使用它。
最佳答案
不确定性能,但您可以使用 Guava 的 ImmutableSet.Builder
:
import com.google.common.collect.ImmutableSet
// ...
Set<Integer> newSet = new ImmutableSet.Builder<Integer>()
.addAll(oldSet)
.add(3)
.build();
当然你也可以为自己写一个辅助方法:
public static <T> Set<T> setWith(Set<T> old, T item) {
return new ImmutableSet.Builder<T>().addAll(old).add(item).build();
}
// ...
Set<Integer> newSet = setWith(oldSet, 3);
关于java - 将单个元素添加到不可变集合的有效且优雅的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10354286/