0
我試圖將位置列表中的所有唯一座標合併到一個HashMap中,該HashMap以座標爲關鍵字,計數爲值。關鍵是由'$'符號連接的經度和緯度。爲什麼containsKey方法不能按預期工作?
//String = coordinates concatinated with '$', Integer = coordinate occurrence count
private HashMap<String, Integer> coordMap = new HashMap<String, Integer>();
...
public void addCoords(double longitude, double latitude) {
//The total count of the state
stateCount++;
String coordsConcat = longitude + "$" + latitude;
//Here we're removing the entry of the existing coord, then re-adding it incremented by one.
if (coordMap.containsKey(coordsConcat)) {
Integer tempCount = coordMap.get(coordsConcat);
tempCount = tempCount + 1;
coordMap.remove(coordsConcat);
coordMap.put(coordsConcat, tempCount);
} else {
coordMap.put(coordsConcat, 1);
}
}
是我遇到的問題是永遠的containsKey返回false,即使通過測試我輸入了兩個相同的經度和緯度座標。
編輯:我試過addCords(0,0);
5次,並且HashMap仍然是空的。
編輯2:雙值只能到第千分之一的地方。
測試用例:
GeoState test = new GeoState("MA");
test.addCoords(0,0);
test.addCoords(0,0);
test.addCoords(0,0);
test.addCoords(0,0);
System.out.println(test.getRegionCoords());
這將返回{}
感謝
請向我們展示'coordMap'的內容,並向我們展示一個帶有傳遞參數的'addCoords'示例調用。 – Tom
看起來不錯。您必須在檢查'containsKey'之前調試並查看地圖中的值。 – user1803551
可能由於精度問題,您無法獲得相同的字符串鍵「coordsConcat」兩次,以進行設置和檢索。 –