将单个元素添加到不可变集合的有效且优雅的方法是什么? [英] What is an efficient and elegant way to add a single element to an immutable set?
问题描述
我有一个可能包含许多元素的不可变集(强制转换为 Set< Integer>
)。我需要一个Collection,其中包含该集合中的元素以及一个附加元素。我有kludgy代码来复制集合,然后附加元素,但我正在寻找使事情尽可能高效的正确方法。
I have an immutable set (cast as a Set<Integer>
) that potentially contains many elements. I need a Collection that contains the elements from that set plus one additional element. I have kludgy code in place to copy the set, then append the element, but I'm looking for The Right Way that keeps things as efficient as possible.
我有番石榴可用,但我不需要使用它。
I have Guava available, though I do not require its use.
推荐答案
不确定性能,但你可以使用Guava的 ImmutableSet.Builder
:
Not sure about performance, but you can use Guava's ImmutableSet.Builder
:
import com.google.common.collect.ImmutableSet
// ...
Set<Integer> newSet = new ImmutableSet.Builder<Integer>()
.addAll(oldSet)
.add(3)
.build();
当然你也可以为自己编写一个辅助方法:
Of course you can also write yourself a helper method for that:
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);
这篇关于将单个元素添加到不可变集合的有效且优雅的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!