【发布时间】:2014-09-27 17:10:45
【问题描述】:
我已经实现了我的多键类如下:
public class ProbabilityIndex {
private int trueLabel;
private int classifiedLabel;
private int classifierIndex;
public ProbabilityIndex(int trueLabel, int classifiedLabel, int classifierIndex) {
this.trueLabel = trueLabel;
this.classifiedLabel = classifiedLabel;
this.classifierIndex = classifierIndex;
}
@Override
public boolean equals(Object obj) {
if ( !obj instanceof ProbabilityIndex)
return false;
if (obj == this)
return true;
ProbabilityIndex rhs = (ProbabilityIndex) obj;
return new EqualsBuilder().
append(trueLabel, rhs.trueLabel).
append(classifiedLabel, rhs.classifiedLabel).
append(classifierIndex, rhs.classifierIndex).
isEquals();
}
@Override
public int hashCode() {
int hashCode = new HashCodeBuilder(17, 31).
append(trueLabel).
append(classifiedLabel).
append(classifierIndex).
toHashCode();
return hashCode;
}
}
请注意,trueLabel、classifiedLabel 和 classifierIndex 都是 0 或 1。
然后,我按如下方式使用我的密钥:
ProbabilityIndex key = new ProbabilityIndex(trueLabel, classifiedLabel, classifierIndex);
probabilities.put(key, new Double(value));
其中probabilities 声明如下:
HashMap<ProbabilityIndex, Double> probabilities;
但是trueLabel、classifiedLabel和classifierIndex的不同组合将元组写入probabilities中的相同位置,从而覆盖现有元组。
我该如何解决这个问题?
最小测试用例:
HashMap<ProbabilityIndex, Double> map = new HashMap<ProbabilityIndex, Double>();
map.put(new ProbabilityIndex(0, 0, 0), new Double(0.1));
map.put(new ProbabilityIndex(0, 0, 1), new Double(0.2));
map.put(new ProbabilityIndex(0, 1, 0), new Double(0.1));
map.put(new ProbabilityIndex(0, 1, 1), new Double(0.2));
map.put(new ProbabilityIndex(1, 0, 0), new Double(0.1));
这会插入 4 个元组而不是 5 个。
【问题讨论】:
-
你能构造一个minimal test-case 来证明这一点吗?
-
什么是 EqualsBuilder?
-
添加了演示
-
我也测试过。它工作正常。我得到以下输出 {ProbabilityIndex@7ba6e=0.1, ProbabilityIndex@7be10=0.1, ProbabilityIndex@7ba6f=0.2, ProbabilityIndex@7ba4f=0.1, ProbabilityIndex@7ba50=0.2}