gpt4 book ai didi

java - 迭代后从 HashSet 中删除失败

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:59:01 27 4
gpt4 key购买 nike

我正在用 Java 编写凝聚聚类算法,但在执行删除操作时遇到了问题。它似乎总是在簇数达到初始数的一半时失败。

在下面的示例代码中,clustersCollection<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,但我不明白为什么。

我通过首先创建 10 个簇来测试此代码,每个簇有一个从 1 到 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 键)中的值时,它不一定在正确的位置,哈希代码将被缓存。您需要删除它,更改它,然后重新插入它。

关于java - 迭代后从 HashSet 中删除失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/754235/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com