简体   繁体   English

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

[英]Content of Collection never updated warning in Intellij IDEA

I created a simple Counter class: 我创建了一个简单的Counter类:

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

    public void increase(T key) {
        put(key, getOrDefault(key, 0l) + 1);
    }
}

In my code, I call the increase() method and then use Map method to access the data, eg 在我的代码中,我调用increase()方法,然后使用Map方法访问数据,例如

  Counter<Integer> counter = new Counter<>();
  for (Integer i: ... some collection ...)
      counter.increase(i);

Intellij highlights the declaration of counter (first line in last snippet) with warning colour, and the tooltip message says Intellij用警告颜色突出显示counter的声明(最后一行的第一行),工具提示消息说明

Contents of collection are queried, but never updated. 查询集合的内容,但从未更新。

Obviously I can just ignore this warning, but is there a way to convince Intellij nothing is wrong with my code? 显然我可以忽略这个警告,但有没有办法说服Intellij我的代码没有任何问题?

I am using 14.0.2 community edition. 我正在使用14.0.2社区版。

IntelliJ IDEA does not realize that the increase() method updates the map, because it is not part of the standard map API. IntelliJ IDEA没有意识到increase()方法更新了地图,因为它不是标准地图API的一部分。 To remove the warning, you can suppress the inspection. 要删除警告,您可以取消检查。

However, a better design would be to make your Counter class encapsulate a HashMap, rather than extend it. 但是,更好的设计是让Counter类封装HashMap,而不是扩展它。 This will make sure that the users of your class will only call the APIs that are appropriate, and will not corrupt your data by calling put() or other modification methods directly. 这将确保您的类的用户只调用适当的API,并且不会通过直接调用put()或其他修改方法来破坏您的数据。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM