【发布时间】:2011-11-30 07:03:35
【问题描述】:
我正在尝试使用 Eclipse 将条目添加到 Java 中的哈希表中。在 put 操作期间,只有一个键被新的键和值覆盖。哈希表的计数得到了正确维护,但是(键,值)对中的一个丢失了。
这是我的示例代码:
ArrayList<Double> list;
Hashtable<Val,ArrayList<Double>> numbers = new Hashtable<Val,ArrayList<Double>>();
while((line = brMyHashval.readLine()) != null)
{
if(!(line.isEmpty()))
{
String[] temp;
temp = line.split(" ");
eDouble = Double.parseDouble(temp[2].toString());
Val key = new Val(Double.parseDouble(temp[0].toString()) ,Double.parseDouble(temp[1].toString()) );
if(!(numbers.containsKey(key)))
{
list = new ArrayList<Double>();
numbers.put(key, list);
}
else
{
list = numbers.get(key);
}
list.add(eDouble);
}
}
我已经习惯在 eclipse 中内置 'hashcode' 和 'equals' 方法来比较类对象。
输入文本文件:
1.0 2.0 9.0
3.0 4.0 9.0
5.0 6.0 9.0
1.0 2.0 8.0
5.0 6.0 8.0
1.0 2.0 7.0
**7.0 8.0 7.0** // After this point a new hash entry gets added for key(7,8), But key (1,2) get deleted from the hashtable, though count gets increased to 4.
3.0 4.0 7.0
5.0 6.0 10.0
1.0 2.0 10.0
1.0 3.0 10.0
1.0 4.0 10.0
为什么密钥会在特定时刻被删除?
[edit] hashcode和equals:我用eclipse自动导入这些方法 // (x,y) 是 (a,b)
class Val
{
double x;
double y;
Val(double X, double Y)
{
x = X;
y = Y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(x);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(y);
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;
Val other = (Val) obj;
if (Double.doubleToLongBits(x) != Double.doubleToLongBits(other.x))
return false;
if (Double.doubleToLongBits(y) != Double.doubleToLongBits(other.y))
return false;
return true;
}
}
【问题讨论】:
-
你的 hashCode 和 equals 是做什么的?
-
什么是“Val”类?和“K”一样吗?
-
是的。对不起。 Val 类是 K 类
-
我无法重现,它按照您描述的方式工作,您希望它在这里工作,所有密钥都创建一次。你能发布一个SSCCE吗?您同时使用 K 类和 Val 类,我认为您显示的代码不是您运行的代码。
-
问题不在于调试器,而在于数据如何存储在 HashMap 中——看我的回答