Search code examples
javahashmap

how to fix this suspicious call to hashmap.get


So this is my HashMap

HashMap<Literal, Double> literalHashMap = new HashMap<>();
for(Literal literal : literalHashSet) {
    if(literal.isTrue(node.state)){ literalHashMap.put(literal, 0.0);}
    else{literalHashMap.put(literal, Double.MAX_VALUE);}
}

Then I do this:

literalHashMap.put((Literal)proposition, updatedCost);

But when I do this:

cost += literalHashMap.get(proposition)

I see a warning saying "suspicious call to hashmap.get".

Any idea how to fix that?


Solution

  • It's saying suspicious call because you pass a Literal Object as the key (literalHashMap.put((Literal)proposition, updatedCost); you downcast proposition so it becomes a Literal object). So, I can assume that proposition is not a Literal object. However, you pass proposition as the key to the HashMap, which is a different kind of object entirely. To fix this: cost += literalHashMap.get((Literal) proposition);. Or, to save a tiny bit of time:

    Literal lit = (Literal) proposition;
    literalHashMap.put((lit, updatedCost);
    cost += literalHashMap.get(list);
    

    To avoid downcasting twice.