gpt4 book ai didi

java - 在构造函数中制作 Set 的一般副本

转载 作者:行者123 更新时间:2023-11-30 06:27:41 25 4
gpt4 key购买 nike

我没有找到这个具体问题的直接答案,所以...假设类:

class MyClass {
private final Set<String> tags;

MyClass(Set<String> initialTags) {
this.tags = ???(initialtags);
}
}

我只想要一个副本,而不关心集合的确切实现,开销最小,所以基本上是 initialTags 具有的任何内部状态的直接副本。我不能使用 clone ,因为 Set 是接口(interface)。这可能吗,还是我必须使用类似 new HashSet<String>(tags); 的东西? , 需要决定类型?

假设:设置项目类型被限制为不可变的。我可以相信调用者不会传递损坏的 initialTags设置实现,我相信它对于此类中的任何内部使用都具有足够好的性能。

我正在考虑尝试反射和 clone(),但这似乎有点脏......

最佳答案

Guava 为此提供了一种方法:

  /**
* Returns an immutable set containing the given elements, in order. Repeated
* occurrences of an element (according to {@link Object#equals}) after the
* first are ignored. This method iterates over {@code elements} at most once.
*
* <p>Note that if {@code s} is a {@code Set<String>}, then {@code
* ImmutableSet.copyOf(s)} returns an {@code ImmutableSet<String>} containing
* each of the strings in {@code s}, while {@code ImmutableSet.of(s)} returns
* a {@code ImmutableSet<Set<String>>} containing one element (the given set
* itself).
*
* <p>Despite the method name, this method attempts to avoid actually copying
* the data when it is safe to do so. The exact circumstances under which a
* copy will or will not be performed are undocumented and subject to change.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static <E> ImmutableSet<E> copyOf(Iterable<? extends E> elements) {
return (elements instanceof Collection)
? copyOf(Collections2.cast(elements))
: copyOf(elements.iterator());
}

关于java - 在构造函数中制作 Set<String> 的一般副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13192474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com