我不明白为什么这段代码会打印错误。这怎么可能?
Set<Set<Place>> clusters = new HashSet<Set<Place>>();
...
Set<Place> max1 = null;
Set<Place> max2 = null;
double maxSim = 0;
for (Set<Place> placesSet : clusters) {
for (Set<Place> placesSet2 : clusters) {
if (placesSet != placesSet2) {
double sim = calculateSim(placesSet, placesSet2);
if (sim >= maxSim) {
maxSim = sim;
max1 = placesSet;
max2 = placesSet2;
}
}
}
}
if (!clusters.remove(max2)) {
System.out.println("ERROR");
}
编辑 现在我检查 sim 是否小于 0 并且 cluster 是否有多个元素。仍然出现错误
Set<Place> max1 = null;
Set<Place> max2 = null;
double maxSim = 0;
for(Set<Place> placesSet : clusters) {
for(Set<Place> placesSet2 : clusters) {
if(!placesSet.equals(placesSet2)) {
double sim = calculateSim(placesSet, placesSet2);
if(sim < 0) sim = 0;
if(sim >= maxSim) {
maxSim = sim;
max1 = placesSet;
max2 = placesSet2;
}
}
}
}
if(!clusters.remove(max2) && clusters.size() >= 1) {
System.out.println("ERROR");
}
下一次编辑:
仍然错误:(
Set<Place> max1 = null;
Set<Place> max2 = null;
double maxSim = 0;
for(Set<Place> placesSet : clusters) {
for(Set<Place> placesSet2 : clusters) {
if(!placesSet.equals(placesSet2)) {
double sim = calculateSim(placesSet, placesSet2);
if(sim < 0) sim = 0;
if(sim >= maxSim) {
maxSim = sim;
max1 = placesSet;
max2 = placesSet2;
}
}
}
}
if(max2 != null && !clusters.remove(max2) && clusters.size() > 1) {
System.out.println("ERROR");
}
最佳答案
似乎有两种可能性:
calculateSim()
返回负值。由于sim
永远不会 >= 0,因此您的 if 语句永远不会被执行,并且max2
将为 null。cluster
有 0 个或 1 个元素。如果没有元素,则循环将永远不会执行。如果有一个元素,循环将执行,但该元素将等于其自身,因此您的第一个 if 将失败。
我建议使用 anding print 语句来监视代码的执行
编辑:请实际将打印语句插入到您的代码中:
Set<Place> max1 = null;
Set<Place> max2 = null;
double maxSim = 0;
System.out.printf("clusters has %d elements:%s%n",clusters.size,clusters);
for(Set<Place> placesSet : clusters) {
for(Set<Place> placesSet2 : clusters) {
System.out.printf("%ncomparing %s and %s%n",placesSet,placesSet2);
if(!placesSet.equals(placesSet2)) {
System.out.println("The sets are not the same");
double sim = calculateSim(placesSet, placesSet2);
System.out.printf("The sim of the sets is %f%n",sim);
if(sim < 0) sim = 0;
System.out.printf("Comparing to the max sim %f%n",maxSim);
if(sim >= maxSim) {
System.out.println("Found new max sim");
maxSim = sim;
max1 = placesSet;
max2 = placesSet2;
}
}
}
}
System.out.printf("The max is %s%n",max2);
if(max2 != null && !clusters.remove(max2) && clusters.size() > 1) {
System.out.println("ERROR");
}
关于java - 从Java中的集合中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20204618/