Content of Collection never updated warning in Intellij IDEA

此生再无相见时 提交于 2019-12-08 15:30:22

问题


I created a simple Counter class:

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.

  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

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?

I am using 14.0.2 community edition.


回答1:


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.

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.




回答2:


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



来源:https://stackoverflow.com/questions/30458975/content-of-collection-never-updated-warning-in-intellij-idea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!