java Intellij IDEA 中的收藏内容从未更新警告

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30458975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:09:52  来源:igfitidea点击:

Content of Collection never updated warning in Intellij IDEA

javaintellij-idea

提问by daphshez

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, e.g.

在我的代码中,我调用了 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

Intellijcounter用警告颜色突出显示(最后一段中的第一行)的声明,工具提示消息说

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 社区版。

回答by yole

IntelliJ IDEA does not realize that the increase() method updates the map, because it is not part of the standard map API. To remove the warning, you can suppress the inspection.

IntelliJ IDEA 没有意识到增加()方法更新地图,因为它不是标准地图 API 的一部分。要删除警告,您可以禁止检查。

However, a better design would be to make your Counter class encapsulate a HashMap, rather than extend it. 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.

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

回答by Semih Okan Pehlivan

You can also try adding @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")to ignore it.

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