迭代之后从HashSet的失败删除
-
09-09-2019 - |
题
我正在写Java中的凝聚聚类算法并且具有与删除操作的麻烦。似乎当簇的数目达到一半的初始数目总是失败。
在以下示例代码,clusters
是Collection<Collection<Integer>>
。
while(clusters.size() > K){
// determine smallest distance between clusters
Collection<Integer> minclust1 = null;
Collection<Integer> minclust2 = null;
double mindist = Double.POSITIVE_INFINITY;
for(Collection<Integer> cluster1 : clusters){
for(Collection<Integer> cluster2 : clusters){
if( cluster1 != cluster2 && getDistance(cluster1, cluster2) < mindist){
minclust1 = cluster1;
minclust2 = cluster2;
mindist = getDistance(cluster1, cluster2);
}
}
}
// merge the two clusters
minclust1.addAll(minclust2);
clusters.remove(minclust2);
}
通过循环几运行后,最终clusters.remove(minclust2)
返回false,但我不明白为什么。
我通过首先从1到10的距离创建群10,各自与一个整数测试此代码是0和1之间的随机数下面是增加了一些println语句后的输出。簇的数目后,打印出的实际簇,合并操作,和clusters.remove(minclust2)的结果。
Clustering: 10 clusters
[[3], [1], [10], [5], [9], [7], [2], [4], [6], [8]]
[5] <- [6]
true
Clustering: 9 clusters
[[3], [1], [10], [5, 6], [9], [7], [2], [4], [8]]
[7] <- [8]
true
Clustering: 8 clusters
[[3], [1], [10], [5, 6], [9], [7, 8], [2], [4]]
[10] <- [9]
true
Clustering: 7 clusters
[[3], [1], [10, 9], [5, 6], [7, 8], [2], [4]]
[5, 6] <- [4]
true
Clustering: 6 clusters
[[3], [1], [10, 9], [5, 6, 4], [7, 8], [2]]
[3] <- [2]
true
Clustering: 5 clusters
[[3, 2], [1], [10, 9], [5, 6, 4], [7, 8]]
[10, 9] <- [5, 6, 4]
false
Clustering: 5 clusters
[[3, 2], [1], [10, 9, 5, 6, 4], [5, 6, 4], [7, 8]]
[10, 9, 5, 6, 4] <- [5, 6, 4]
false
Clustering: 5 clusters
[[3, 2], [1], [10, 9, 5, 6, 4, 5, 6, 4], [5, 6, 4], [7, 8]]
[10, 9, 5, 6, 4, 5, 6, 4] <- [5, 6, 4]
false
在该[10,9,5,6,4,5,6,4,...]仅有无限从那里生长。
修改:澄清,我使用的用于在群集的每个群集(一个HashSet<Integer>
一个HashSet<HashSet<Integer>>)
强>
解决方案
阿。当你改变的值已经处于Set
(或Map
键),那么它是在正确的位置和Hash码并不一定会被缓存。您需要删除它,改变它,然后重新插入。
其他提示
在所示的测试中,remove
失败第一次尝试,以除去含有多于一个整数的集合。这是总是这样?
什么是具体类型中使用的类别的?
明显的问题存在着clusters.remove
可能是使用equals
找到要删除的元素。不幸的是在收藏equals
一般比较元素是否是相同的,而不是如果是同一个集合(我相信C#使得在这方面是更好的选择)。
一个简单的办法是创建clusters
作为Collections.newSetFromMap(new IdentityHashMap<Collection<Integer>, Boolean>())
(我想)。
不隶属于 StackOverflow