[英]Hashtable returning null but object key is present
編輯:FML! 我的哈希碼實現使用小寫字母c。 -.-
我一直在嘗試學習TDD,並且一直在關注Kent Beck的“通過示例”一書; 這很好!
但是,我似乎無法取得進展,因為訪問哈希表時某個值返回null。 我已經運行了一個調試會話,並且帶有值的對象顯然在那里,但結果為null。
構建和訪問的代碼為:
public void addRate(String from, String to, int rate){
this.rates.put(new Pair(from, to), new Integer(rate));
}
從到分別是“ GBP”和“ USD”。 還通過調試驗證。
上面的測試用例:
@Test
public void testreduceMoneyDifferentCurrency(){
Bank bank = new Bank();
bank.addRate("GBP", "USD", 2);
Money result = bank.reduce(Money.gbpound(2), "USD");
assertEquals(Money.dollar(1), result);
}
銀行中的reduce方法調用方法率:
public Money reduce(Bank bank, String to){
int rate = bank.rate(this.currency, to);
return new Money(this.amount / rate, to);
}
問題出在哪里:
public int rate(String from, String to){
if (from.equals(to)) return 1;
Integer rate = (Integer) this.rates.get(new Pair(from, to));
return rate.intValue();
}
第一行處理美元->美元轉換等。
Pair對象是為用作鍵而構建的2個字符串。
我沒有使用過很多表,但是我看不出問題是什么,我肯定知道值在哈希表中,但是“ rate”總是返回空值。
我看不見樹木的樹木。 :)有人可以指出我正確的方向嗎?
我認為問題出在Pair
方法中。 執行此操作時:
this.rates.get(new Pair(from, to));
您正在創建Pair
的新實例,該實例與您在addRate
方法中放入地圖中的addRate
。
如果希望代碼正常工作,則必須使用Pair
類的相同實例,或者在Pair
類上正確實現equals
和hashCode
方法。
以下是對HashMap的內部工作以及使它工作所需要做的一些更深入的了解: https : //stackoverflow.com/a/6493946/2266098
Java保留對象的引用。 因此,當您嘗試執行此操作時, this.rates.get(new Pair(from, to));
您基本上是在創建一個新的Pair
實例,該實例在您的HashMap
中不作為鍵存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.