所以,我正在尝试使用 aHashMap
将我自己的值映射Object
到一个String
值。我的对象在下面(为简洁起见,删除了一些代码)
public class RouteHeadsignPair {
String route;
String headsign;
public RouteHeadsignPair(String n_route, String n_headsign) {
route = n_route.toLowerCase();
headsign = n_headsign.toLowerCase();
}
public String getRoute () {
return route;
}
public String getHeadsign() {
return headsign;
}
public boolean equals(RouteHeadsignPair other) {
return(other.getRoute().equals(route) && other.getHeadsign().equals(headsign));
}
public int hashCode() {
return(route.hashCode());
}
}
我通过从文本文件加载数据将一堆这些对象映射到字符串。稍后,基于(独立)用户输入,我尝试HashMap
使用RouteHeadsignPair
Object 进行查询。containsKey() 返回 false 而 get() 返回 null,就好像我从未将键添加到地图中一样。但是,奇怪的是,如果我使用下面的代码迭代地图(其中newKey
是RouteHeadsignPair
由用户输入制作的)
RouteHeadsignPair foundKey = null;
Iterator<RouteHeadsignPair> keysInMap = routeHeadsignToStopIdMap.keySet().iterator();
while(keysInMap.hasNext()) {
RouteHeadsignPair currKey = keysInMap.next();
if(currKey.equals(newKey)) {
System.err.println("Did find a key with an equals() == true!");
foundKey = currKey;
}
}
System.err.println("Value in map? " + routeHeadsignToStopIdMap.containsKey(newKey) + "( hashcode = " + newKey.hashCode() +
", equals = " + newKey.equals(foundKey) + ")");
System.err.println("foundKey in map? " + routeHeadsignToStopIdMap.containsKey(foundKey) + "( hashcode = " + foundKey.hashCode() +
", equals = " + foundKey.equals(newKey) + ")" );
我为代码格式道歉,太晚了,我变得暴躁
我得到以下输出
Did find a key with an equals() == true!
接着
Value in map? false( hashcode = 1695, equals = true)
foundKey in map? true( hashcode = 1695, equals = true)
因此,如果我遍历键并查找返回的键equals()
,我确实找到了一个,并且这hashCode()
两个键是相同的。如果和和返回truehashCode()
相同,不应该返回一个值并返回true吗?我在这里做错了什么?newKey
foundKey
foundKey.equals(newKey)
HashMap.get(key)
containsKey()