Search code examples
javahashmapcontainscontainskey

Why won't the containsKey method work as expected?


I'm trying to add up all the unique coordinates from a list of locations into a single HashMap that has the coordinate as the key, and the count as the value. The key is the longitude and latitude concatenated by the '$' symbol.

//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);
        }


    }

The issue that I am having is that containsKey always return false, even though through testing I entered two of the same longitude and latitude coordinates.

EDIT: I tried addCords(0,0); 5 times, and the HashMap is still empty.

EDIT 2: The double values are only to the thousandth's place.

Test Case:

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());

This will return {} Thanks


Solution

  • This is most probably a precision issue. You might want to check the values of coordsConcat before you put them into the HashMap, after you put it into the HashMap and before you check for containsKey.

    Odds are there is some minor (or major) mismatch between the values which is causing this issue.