ahm*_*l88 2 java collections declaration hashmap sonarlint
我已经知道如何HashMap使用以下两种方法之一来初始化Java
// 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();
Run Code Online (Sandbox Code Playgroud)
我的问题
什么是最佳做法
根据Eclipse Marker
类型安全:HashMap类型的表达式需要未经检查的转换以符合HashMap
new HashMap<String, Integer>();
Run Code Online (Sandbox Code Playgroud)
但根据Sonar Linter的说法
使用菱形运算符("<>")替换此构造函数调用中的类型规范.
new HashMap();
Run Code Online (Sandbox Code Playgroud)
哪一个是最好的?为什么?
使用Java 7钻石运算符:
HashMap<String, Integer> hashMap2 = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)
Diamond <>允许编译器隐式推断类型
请参阅:通用实例创建的类型推断