java - 在构造函数中制作 Set<String> 的常规副本

标签 java collections clone defensive-copy

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

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/

相关文章:

Java - 寻找比 PriorityQueue 更快的东西

c# - 这是 AutoMapper 2.0.0 和 2.2.0 之间的重大变化吗?

java - clone() : ArrayList. clone() 我以为做了浅拷贝

javascript - jquery 克隆 + 实时问题

Java 将 Set<Set<String>> 转换为 List<List<String>>

jquery - 使用 jQuery 克隆多个表行

java - 如何在 Eclipse Helios 中引用另一个项目中的库?

java - java中的图像操作

java - ArrayList 删除方法不起作用?

java - 从空格分隔值读取字符数组