gpt4 book ai didi

Java HashMap 初始化?

转载 作者:行者123 更新时间:2023-11-30 06:02:43 32 4
gpt4 key购买 nike

我已经知道如何使用以下两种方法之一初始化 Java HashMap

// way 1: apply generic type saftey
HashMap<String, Integer> hashMap1 = new HashMap<String, Integer>();

// way 2: general without apply generic type saftey
HashMap<String, Integer> hashMap2 = new HashMap();

我的问题
最佳实践是什么

根据 eclipse 标记

Type safety: The expression of type HashMap needs unchecked conversion to conform to HashMap

enter image description here所以建议使用

new HashMap<String, Integer>(); 

但是根据Sonar Linter

Replace the type specification in this constructor call with the diamond operator ("<>").

enter image description here所以建议使用

new HashMap();

哪个最好?为什么?

最佳答案

使用 Java 7 菱形运算符:

HashMap<String, Integer> hashMap2 = new HashMap<>();

Diamond <> 允许编译器隐式推断类型

参见:Type Inference for Generic Instance Creation

关于Java HashMap 初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53865095/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com