集合的内容在Intellij IDEA中从未更新过警告 [英] Content of Collection never updated warning in Intellij IDEA

查看:142
本文介绍了集合的内容在Intellij IDEA中从未更新过警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的Counter类:

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);
    }
}

在我的代码中,我调用了gain()方法,然后使用Map方法访问数据,例如

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用警告颜色突出显示counter(最后一个片段的第一行)的声明,并且工具提示消息显示

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.

很明显,我可以忽略此警告,但是有没有办法说服Intellij代码没有问题呢?

Obviously I can just ignore this warning, but is there a way to convince Intellij nothing is wrong with my code?

我正在使用14.0.2社区版.

I am using 14.0.2 community edition.

推荐答案

IntelliJ IDEA并未意识到gain()方法会更新地图,因为它不是标准地图API的一部分.要消除警告,您可以取消检查.

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.

但是,更好的设计是使Counter类封装HashMap,而不是对其进行扩展.这将确保您的类的用户将仅调用适当的API,并且不会通过直接调用put()或其他修改方法来破坏您的数据.

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.

这篇关于集合的内容在Intellij IDEA中从未更新过警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆