英文:
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<Long,Integer> 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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论