我在使用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