[英]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.