Skip to main content
3 of 3
little typo
jeprubio
  • 18.1k
  • 5
  • 51
  • 62

Java : How to check if a key is exists in a Hashmap

I have defined a hashmap of type :

HashMap<Position, Double> list = new HashMap<>(); 

Where Position is class with two attributes x and y .

I would like to verify if a position is already in the list or not, I have tried this :

public void addToList(Position p, double somme) { if (this.list.containsKey(p)) { this.list.replace(p, this.list.get(p) + somme);//add the old value somme } else { this.list.put(p, somme); } } 

I think I should be more specific and verify values of x any y instead of check if key is exist because each time the check failed to detect an exist position.

How can check if a position is in the list or not?

Gismail
  • 99
  • 1
  • 10