Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content of Collection never updated warning in Intellij IDEA

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.

like image 271
daphshez Avatar asked May 26 '15 12:05

daphshez


2 Answers

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.

like image 120
yole Avatar answered Nov 15 '22 08:11

yole


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

like image 5
Semih Okan Pehlivan Avatar answered Nov 15 '22 08:11

Semih Okan Pehlivan