2015-10-18 104 views
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()); 

這將返回{} 感謝

+1

請向我們展示'coordMap'的內容,並向我們展示一個帶有傳遞參數的'addCoords'示例調用。 – Tom

+0

看起來不錯。您必須在檢查'containsKey'之前調試並查看地圖中的值。 – user1803551

+0

可能由於精度問題,您無法獲得相同的字符串鍵「coordsConcat」兩次,以進行設置和檢索。 –

回答

1

這是最有可能精度問題。在將它們放入HashMap之前,您將它放入HashMap並檢查containsKey之前,可能需要檢查coordsConcat的值。

機率是造成這個問題的值之間的一些小的(或主要的)不匹配。

相關問題