Java的HashMap的初始化?

Ahmednbil88:

我已经知道如何初始化的Java HashMap使用下列2种方式一个

// 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的标记

类型安全:类型的HashMap的表达需要选中转换为符合的HashMap

在这里输入图像描述 因此,它建议使用

new HashMap<String, Integer>(); 

但根据声纳短绒

与金刚石操作者替换此构造呼叫类型规范(“<>”)。

在这里输入图像描述 因此,它建议使用

new HashMap();

哪一个是最好的?为什么?

安东Hlinisty:

使用Java 7钻石操作:

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

金刚石<>允许编译器推断类型隐含地

参见:类型推断通用实例创建

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章