【发布时间】:2012-01-12 10:15:46
【问题描述】:
我知道 Wikipedia 上的 Union Find 算法,并且可以找到它们的小型实现,但是 Java 本身是否对其 Set 使用了类似的算法?如果是这样,我宁愿使用 Java Sets 而无需重新编码轮子...
【问题讨论】:
-
你的意思是不相交集操作吗?
标签: java algorithm math data-structures
我知道 Wikipedia 上的 Union Find 算法,并且可以找到它们的小型实现,但是 Java 本身是否对其 Set 使用了类似的算法?如果是这样,我宁愿使用 Java Sets 而无需重新编码轮子...
【问题讨论】:
标签: java algorithm math data-structures
Java 的 Set 接口支持与 Union Find 结构完全不同的操作(因此适用于完全不同的用例)。
【讨论】:
AFAIK 不,要创建两个集合的并集,常见的方法是复制一个集合并添加第二个集合的所有元素。 (或将两个集合的所有元素复制到同一个集合)例如
Set<E> set1, set2;
Set<E> union = new HashSet<E>(set1);
union.addAll(set2);
【讨论】:
我同意第一个答案。此外,要在 Set 中查找元素,您应该使用 contains 方法。它的签名是:
public boolean contains(Object o)
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).
Specified by:
contains in interface Collection<E>
Parameters:
o - element whose presence in this set is to be tested.
Returns:
true if this set contains the specified element.
Throws:
ClassCastException - if the type of the specified element is incompatible with this set (optional).
NullPointerException - if the specified element is null and this set does not support null elements (optional).
此外,这三个 Set 的实现方式完全不同。将其元素存储在哈希表中的 HashSet 是性能最好的实现;但是它不保证迭代的顺序。 TreeSet 将其元素存储在红黑树中,根据元素的值对其元素进行排序;它比 HashSet 慢得多。 LinkedHashSet 被实现为一个带有链表的哈希表,它根据元素插入集合的顺序(插入顺序)对其元素进行排序。 LinkedHashSet 将其客户从 HashSet 提供的未指定的、通常混乱的排序中解放出来,而代价只是略高一些。
【讨论】: