我正在学习数据结构和算法,并尝试在 Java 中实现不相交的数据结构。这是我做同样事情的代码-
import java.util.*;
public class DisjointSet<T> {
Set<LinkedHashSet<T>> allSets;
DisjointSet() {
allSets = new HashSet<LinkedHashSet<T>>();
}
public void makeSet(T t) {
Iterator itr = allSets.iterator();
while (itr.hasNext()) {
LinkedHashSet set = (LinkedHashSet) itr.next();
if (set.contains(t)) {
return;
}
}
LinkedHashSet<T> set = new LinkedHashSet<T>();
set.add(t);
allSets.add(set);
}
public T findSet(T t) {
Iterator itr = allSets.iterator();
while (itr.hasNext()) {
LinkedHashSet set = (LinkedHashSet) itr.next();
if (set.contains(t)) {
Iterator itr1 = set.iterator();
T t1 = (T) itr1.next();
return t1;
}
}
return null;
}
public void union(T t1, T t2) {
LinkedHashSet<T> set1 = null, set2 = null;
Iterator itr = allSets.iterator();
while (itr.hasNext()) {
LinkedHashSet set = (LinkedHashSet) itr.next();
if (set.contains(t1)) {
set1 = (LinkedHashSet<T>) set;
System.out.println("Got set1:: " + set1);
} else if (set.contains(t2)) {
set2 = (LinkedHashSet<T>) set;
System.out.println("Got set2:: " + set2);
}
}
if (null != set1) {
System.out.println("Adding set2 to set1");
set1.addAll(set2);
if (null != set2) {
System.out.println("Removing set2");
System.out.println(allSets.remove(set2));
}
}
}
public void viewAllSets() {
System.out.println(this.allSets);
}
}
这是我正在运行以测试我的实现的代码-
public class DisjointTest {
public static void main(String [] args) {
DisjointSet<Integer> dsets = new DisjointSet<Integer>();
dsets.makeSet(30);
dsets.makeSet(600);
dsets.makeSet(20);
dsets.makeSet(25);
dsets.makeSet(90);
dsets.makeSet(100);
dsets.makeSet(1);
dsets.viewAllSets();
System.out.println();
System.out.println(dsets.findSet(25));
dsets.union(20, 25);
dsets.viewAllSets();
System.out.println();
System.out.println(dsets.findSet(25));
dsets.union(1, 100);
dsets.viewAllSets();
System.out.println();
dsets.union(20, 100);
dsets.viewAllSets();
System.out.println(dsets.findSet(100));
System.out.println();
dsets.union(30, 90);
dsets.viewAllSets();
System.out.println();
dsets.union(1, 90);
dsets.viewAllSets();
}
}
当我尝试将一个集合与另一个集合合并时,比如说 set2,它有 2 个或更多元素,集合会正确合并,但即使在调用之后 set2 也不会从集合集合中删除allsets.remove(set2)
但是,如果要合并的集合,即;set2,只有 1 个元素,allSets.remove(set2)
成功从集合集合中移除 set2。
这是我的代码的输出,它确认了我的问题-
[[1], [100], [20], [25], [600], [90], [30]]
25
Got set1:: [20]
Got set2:: [25]
Adding set2 to set1
Removing set2
true
[[1], [100], [20, 25], [600], [90], [30]]
20
Got set1:: [1]
Got set2:: [100]
Adding set2 to set1
Removing set2
true
[[1, 100], [20, 25], [600], [90], [30]]
Got set2:: [1, 100]
Got set1:: [20, 25]
Adding set2 to set1
Removing set2
false
[[1, 100], [20, 25, 1, 100], [600], [90], [30]]
1
Got set1:: [20, 25, 1, 100]
Got set2:: [90]
Adding set2 to set1
Removing set2
true
[[1, 100], [20, 25, 1, 100, 90], [600], [30]]
我无法理解为什么HashSet.remove(LinkedHashSet)
无法删除LinkedHashSet
带有多个元素的 a,但成功地删除了LinkedHashSet
带有 1 个元素的 a。
任何帮助将不胜感激。非常感谢。