有两组具有相同的单个元素。
Set<Activity> a = new HashSet<Activity>();
a.add(new Activity("X", 1, 2));
Set<Activity> b = new HashSet<Activity>();
b.add(new Activity("X", 1, 2));
return a.containsAll(b); //gives false??
当实际上这些集是相同的时,containsAll方法返回false?
我已经阅读了类似问题的答案,其中一个是HashSet contains problem with custom objects,HashSet contains method, strange behavior,我理解HashSet的工作原理。您计算存储桶的哈希值,然后使用重写的equals()方法搜索对象。
活动类以这种方式实现:
public class Activity implements Comparable<Activity> {
private final double maxDuration;
private final double normalDuration;
private final String label;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((label == null) ? 0 : label.hashCode());
long temp;
temp = Double.doubleToLongBits(maxDuration);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(normalDuration);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Activity other = (Activity) obj;
if (label == null) {
if (other.label != null)
return false;
} else if (!label.equals(other.label))
return false;
if (Double.doubleToLongBits(maxDuration) != Double
.doubleToLongBits(other.maxDuration))
return false;
if (Double.doubleToLongBits(normalDuration) != Double
.doubleToLongBits(other.normalDuration))
return false;
return true;
}
public Activity(String label, double d, double e) {
this.maxDuration = e;
this.normalDuration = d;
this.label = label;
}
}
hashCode和equals函数的输入(如上所示)是相同的,函数是确定性的,因此为什么会发生这种情况?绝对没有办法改变Activity对象,因为我明确地将它们变为不可变。所以我完全迷失了为什么会这样。
提前感谢您的帮助。