在Java中声明ConcurrentHashMap时,我是否必须添加final关键字?

huangapple go评论114阅读模式
英文:

should I must add final keyword when declaring a ConcurrentHashMap in Java

问题

以下是翻译好的内容:

当我在Java 8类中像这样声明一个ConcurrentHashMap

private final static ConcurrentHashMap<Long, Integer> signRatioMap = new ConcurrentHashMap();

我发现如果没有使用final关键字,它不能正常工作。我应该添加final关键字吗?这样做有什么优势?

英文:

When I declare a ConcurrentHashMap in Java 8 class like this:

private final static ConcurrentHashMap&lt;Long,Integer&gt; signRatioMap = new ConcurrentHashMap();

I found without final it doesn't work fine. should I add final keywords? what is the advantage?

答案1

得分: 1

Final关键字仅用于防止变量被重新赋值。如果您不需要重新赋值变量,请将其声明为final。

英文:

The Final keyword does nothing but prevent a variable from being reassigned. If you don't need to reassign the variable, make it final.

答案2

得分: 1

通常情况下,将变量声明为 final 是一种良好的编码实践,也可能带来一些性能上的好处(详见 https://stackoverflow.com/a/4279442/508328)。

然而在你的情况下稍有不同,因为 Java 的哈希映射实现只会增长其内部结构,而不会收缩,这导致其扫描性能持续恶化。因此,如果你的映射表经常发生变化,最好是时不时地重新创建它,在这种情况下它就不能声明为 final

英文:

Generally, making a variable final is a good coding practice and also may lead to some performance benefits (see the https://stackoverflow.com/a/4279442/508328 for details).

In your case, however, the situation is slightly different because Java's implementation of hash map can only grow its internal structure and never shrinks down, which leads to the continuous deterioration of its scan performance. So if your map is going to be changed often, it'd be better to recreate it now and then, and in that case it can't be final.

huangapple
  • 本文由 发表于 2020年10月23日 11:46:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/64493581.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定