问题:
我想在 java 中有一个像这样的 map :
Map<Double,List<MyClass>> map = new HashMap<Double,List<MyClass>>();
我想基本上根据 double 值对 MyClass 对象进行分组。
但是 Key (Double) 是实验数据,里面有噪声。我希望将项目添加到同一个列表,即使键有点不同。
例如:
如果我在 map 中已经有了 key = 1300.5
,如果我要添加的新值是 newKey = 1300.7
比如说,
当我说 map.containsKey(newKey)
我希望 map 返回 true
此外,当我说 map.get(newKey)
时,我希望它返回 key=1300.5
的相应列表值,然后我将向其添加一个新的 我的类(class)
。
到目前为止我做了什么:
我创建了这个类,它现在将成为我的 key 而不是 Double
class NearestFreq{
Double freq;
@Override
public boolean equals(Object obj) {
System.out.println("inside equals method...");
if(Math.abs(this.freq-((NearestFreq)obj).freq)<Constants.range){
return true;
}
else {
return false;
}
}
public NearestFreq(Double freq) {
super();
this.freq = freq;
}
}
我预计这将使 map 假设两个键相同(如果它们在误差线内)。我将 map 更改为:
Map<NearestFreq,List<MyClass>> map = new HashMap<NearestFreq,List<MyClass>();
但我发现 map 的 containsKey() 调用没有调用 NearestFreq 的 .equals()
方法("inside equals method..."
从未被打印出来),我不明白为什么。
谁能告诉我如何实现这个?
最佳答案
您使用的是 HashMap,因此 map 插入调用 hashCode
方法来确定项目在 map 中的位置。 equals
仅在发生碰撞时调用。
作为 Java 中的一般规则,如果您覆盖 equals
或 hashCode
,您也应该始终覆盖另一个,以确保 a.hashCode() = = b.hashCode()
如果 a.equals(b)
为真。
关于java - Java 中键上带有错误栏的映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30158131/