收集的内容从未在Intellij IDEA中更新警告

dap*_*hez 11 java intellij-idea

我创建了一个简单的Counter类:

public class Counter<T> extends HashMap<T, Long> {
    public Counter() {
    }

    public void increase(T key) {
        put(key, getOrDefault(key, 0l) + 1);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我调用increase()方法,然后使用Map方法访问数据,例如

  Counter<Integer> counter = new Counter<>();
  for (Integer i: ... some collection ...)
      counter.increase(i);
Run Code Online (Sandbox Code Playgroud)

Intellij counter用警告颜色突出显示(最后一行代码片段)的声明,工具提示消息说明

查询集合的内容,但从未更新.

显然我可以忽略这个警告,但有没有办法说服Intellij我的代码没有任何问题?

我正在使用14.0.2社区版.

yol*_*ole 7

IntelliJ IDEA没有意识到increase()方法更新了地图,因为它不是标准地图API的一部分.要删除警告,您可以取消检查.

但是,更好的设计是让Counter类封装HashMap,而不是扩展它.这将确保您的类的用户只调用适当的API,并且不会通过直接调用put()或其他修改方法来破坏您的数据.


Sem*_*van 6

您也可以尝试添加@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")以忽略它。