我在使用Java Collections API時遇到此問題。基本上這是一個實現Kruskal算法尋找MST的支持方法。我創建了這個類來實現union/find算法。Java集合API HashSet刪除方法
我的問題,因爲我能找到解決辦法,是否有人知道爲什麼「聯合」方法中的remove方法不能一致地工作。這是在運行時它會刪除一些元素而不是其他元素。例如,我爲了一個涉及城市的任務實施了這個任務,似乎並不喜歡去除一些城市。特別是它偶然偶然發現了幾套不同的套裝,但總是同樣的套裝。我想知道這是否是一個對象引用問題,也就是說我是否在測試錯誤的東西,但我無法繞過它。
我知道我的其餘工作是正確的,因爲我可以用消除元素的循環替換它,並且算法執行完美。然而,可能會有稍差的表現。
我想知道是否有人能看到一個錯誤。另外我應該注意到,我從不同的類中調用它,但是,調用是使用find方法檢索的元素進行的。請注意,find方法必須正常工作,因爲只需更改remove方法就可以使整個工作正常工作,即找到並返回適當的對象。
感謝
奧斯卡
/*
* A constructor for creating a new object of this class.
*/
DisjointSets()
{
underlying = new HashSet<HashSet<String>>();
}
/*
* A method for adding a set to this DisjointSets object
*/
void add(HashSet<String> h)
{
underlying.add(h);
}
/*
* A method for finding an element in this DisjointSet object.
*/
HashSet<String> find(String s)
{
// Check each set in the DisjointSets object
for(HashSet<String> h: underlying)
{
if(h.contains(s))
{
return h;
}
}
return null;
}
/*
* A method for combining to subsets of the DisjointSets
*/
void union(HashSet<String> h1, HashSet<String> h2)
{
System.out.print("CHECK ON DS\n");
System.out.print("*********************\n");
System.out.print("H1 is : { ");
for (HashSet<String> n: underlying)
{
System.out.print("Set is : { ");
for (String h : n)
{
System.out.print(h + " , ");
}
System.out.print("} \n ");
}
// Add the objects of h1 to h2
// DOES NOT WORK CONSISTENTLY
h1.addAll(h2);
underlying.remove(h2);
}
}
和我一起
HashSet<HashSet<String>> temp = new HashSet<HashSet<String>>();
for(HashSet<String> f: underlying)
{
if(f != h2)
{
temp.add(f);
}
}
underlying = temp;
@lwburk感謝您的格式幫助,讚賞。 – oscarcollings 2011-04-21 21:39:21