2

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

class MyClass {
    private final Set<String> tags;

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

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

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

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

4

3 回答 3

4

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());
  }
于 2012-11-02T09:39:09.773 回答
1

根据 initialTags 的预期大小,您可能更喜欢不同的实现;下面的代码显示了基于构造函数的副本的更快时间i is < 100000,但克隆在 时更快i > 1000000。如果您真的想使用clone,您可以始终使用isinstance来确定它是(6)个众所周知的具体实现(即实现cloneable)中的哪一个,除此之外,您无法保证initialTags拥有它。

static Set<String> byCloning(HashSet<String> initialTags) {

    return (Set<String>) initialTags.clone();
}

static Set<String> byConstructor(Set<String> initialTags) {

    return new HashSet<String>(initialTags);
}

public static void main(String[] args) {

    int N = Integer.parseInt(args[0]);

    HashSet<String> mySet = new HashSet<String>();
    for (int n = 0 ; n < N ; n++) mySet.add(Integer.toString(n));

    long start = System.currentTimeMillis();
    byCloning(mySet);
    long end = System.currentTimeMillis();
    System.out.println(" time take in milli seconds for cloning = " + (end-start) );

    start = System.currentTimeMillis();
    byConstructor(mySet);
    end = System.currentTimeMillis();
    System.out.println(" time take in milli seconds by constructor = " + (end-start) );
}
于 2012-11-02T10:05:10.370 回答
0

根据您需要的集合访问类型来决定类型,或者您可以尝试使用Collections.unmodifiableSet () :

class MyClass {
    private final Set<String> tags;

    MyClass(Set<String> initialTags) {
        this.tags = Collections.unmodifiableSet(initialTags);
    }
}
于 2012-11-02T09:31:57.443 回答