Java HashMap get works but containsKey does not

后端 未结 9 1299
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 05:41

I am trying to locate a key in a HashMap. I can print the selected key by using \'get\' but when I use \'containsKey\' in an if statement, it is not found.

I KNOW

9条回答
  •  猫巷女王i
    2020-12-06 06:05

    containsKey uses the method equals to compare the param with the entries in the key set. So the Location class needs to have a equals method that is good. The default equals method in java.lang.Object only returns true when both objects are the same object. In this case you probably have 2 different instances that needs to be compared and need a custom equals method.

提交回复
热议问题