这些初始化HashMap的方式有什么区别? [英] What's the difference between these ways of initializing a HashMap?
问题描述
我为我的程序使用了一个HashMap,它工作正常,但我不明白这些HashMap的初始化之间的区别。
假设我正在实施一个字符作为键和一个整数作为值的HashMap。
$ b
HashMap< Character,Integer> alphabet1 =新的HashMap();
HashMap<字符,整数> alphabet1 = new HashMap< Character,Integer>();
HashMap alphabet1 = new HashMap< Character,Integer>();
Map alphabet1 = new HashMap< Character,Integer>();
HashMap alphabet1 = new HashMap< Character,Integer>();
HashMap alphabet1 = new HashMap();
Map alphabet1 = new HashMap();
涉及 HashMap
或
Map
没有类型参数(尖括号<和>和它们之间的部分)是绘制类型,不应该使用。原始类型不是通用的,可以让你做不安全的事情。
正确的方式是
映射< Character,Integer> alphabet1 = new HashMap< Character,Integer>();
HashMap<字符,整数> alphabet1 = new HashMap< Character,Integer>();
第一个使用接口Map作为参考类型。 它通常更习惯和风格很好。 p>
Map<字符,整数> ; alphabet1 = new HashMap<>();
HashMap<字符,整数> alphabet1 = new HashMap<>();
这或多或少与前两种正确的方式相同。左侧参考类型的参数隐式提供给右侧的构造函数。
I used a HashMap for my program and it works fine, but I don't understand the difference between these initializations of HashMap.
Let's say I'm implementing a HashMap with a character as a key and an integer as a value. What's the difference between these?
HashMap<Character, Integer> alphabet1 = new HashMap();
HashMap<Character, Integer> alphabet1 = new HashMap<Character, Integer>();
HashMap alphabet1 = new HashMap<Character, Integer>();
Map alphabet1 = new HashMap<Character, Integer>();
HashMap alphabet1 = new HashMap<Character, Integer>();
HashMap alphabet1 = new HashMap();
Map alphabet1 = new HashMap();
Anything involving HashMap
or Map
without a type argument (the angle brackets < and > and the part between them) is a raw type and shouldn't be used. A raw type is not generic and lets you do unsafe things.
The "correct" ways are
Map<Character, Integer> alphabet1 = new HashMap<Character, Integer>();
HashMap<Character, Integer> alphabet1 = new HashMap<Character, Integer>();
The first uses the interface Map as the reference type. It is generally more idiomatic and a good style.
Also another way you did not mention, using the Java 7 diamond operator
Map<Character, Integer> alphabet1 = new HashMap<>();
HashMap<Character, Integer> alphabet1 = new HashMap<>();
Which is more or less equivalent to the first two correct ways. The arguments to the reference type on the left-hand side are supplied implicitly to the constructor on the right-hand side.
这篇关于这些初始化HashMap的方式有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!