【问题标题】:Java HashMap initialization?Java HashMap 初始化?
【发布时间】:2018-12-20 08:42:15
【问题描述】:

我已经知道如何使用以下 2 种方式之一来初始化 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 Marker

类型安全:HashMap 类型的表达式需要未经检查的转换 符合HashMap

所以建议使用

new HashMap<String, Integer>(); 

但根据 Sonar Linter

将此构造函数调用中的类型规范替换为 菱形运算符(“”)。

所以建议使用

new HashMap();

哪个是最好的?为什么?

【问题讨论】:

标签: java collections hashmap declaration sonarlint


【解决方案1】:

使用 Java 7 菱形运算符:

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

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

见:Type Inference for Generic Instance Creation

【讨论】:

    猜你喜欢
    • 2015-01-15
    • 2016-08-25
    • 2022-12-06
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 2010-09-30
    相关资源
    最近更新 更多