我正在嘗試使用Eclipse將條目添加到Java中的哈希表。在投入操作期間,只有一個密鑰被新的密鑰和值覆蓋。散列表的計數保持正確,但其中一個(鍵,值)對丟失。Java Hashtable在'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);
}
}
我已經使用到內置「哈希碼」和「等於」方法在蝕用於比較類對象。
輸入文本文件:
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
爲什麼關鍵獲取該特定即時刪除。?
[編輯]哈希碼和等於:我用蝕自動導入這些方法 //(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呢? – Thilo
什麼是「Val」班?它與「K」相同嗎? – dmeister
是的。抱歉。 Val類是K類 – SyncMaster