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.

mmBs
  • 8,421
  • 6
  • 38
  • 46
daphshez
  • 9,272
  • 11
  • 47
  • 65

2 Answers2

8

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.

yole
  • 92,896
  • 20
  • 260
  • 197
  • Thanks for the advice. In my scenario I am comfortable with users having access to the HashMap if they like, and I have not much interest and writing many methods that only delegate :-) – daphshez May 27 '15 at 07:39
  • 1
    Is there any @SuppressWarning argument to deal with this inspection? – Sebastian Oct 17 '16 at 11:13
  • 1
    Yes. You can press Alt-Enter on any inspection highlight and select the suppress action from the menu. – yole Oct 17 '16 at 13:42
6

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

Muhammad bin Yusrat
  • 1,433
  • 1
  • 14
  • 19
sopehl
  • 1,067
  • 1
  • 13
  • 18
  • Where do you put this suppression? And where can I find a list of suppression messages as this doesn't seem to do it for me. – SMBiggs Jun 27 '18 at 22:06
  • 1
    @ScottBiggs I guess we'll never know – Denny Sep 02 '18 at 15:13
  • @ScottBiggs, you can browse to this stackoverflow link (https://stackoverflow.com/questions/2037326/all-suppresswarnings-values) to ignore many SuppressWarnings cases. The SuppressWarnings annotation is annotated by Target(value={TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE}), so you can put to many piece of your code like method or class. – sopehl Sep 11 '18 at 10:37