这些泛型声明之间有什么区别?

Kum*_*mar 3 java generics

Map<String, Integer> map = new HashMap<String, Integer>();
Run Code Online (Sandbox Code Playgroud)

Map<String, Integer> map = new HashMap();
Run Code Online (Sandbox Code Playgroud)

由于这对我来说是新的,我不确定这两个陈述之间的实际区别是什么,因为两者似乎都运行良好.我试图在其他地方找到,但找不到任何具体的答案.

ars*_*jii 8

第二个变体使用原始类型,通常很糟糕.实际上,原始类型仅出于向后兼容性的原因而存在.

考虑一下:

Map<Double, Double> other = new HashMap<Double, Double>();
other.put(42.0, 42.0);

Map<String, Integer> map = new HashMap(other);
Run Code Online (Sandbox Code Playgroud)

使用原始类型,我们设法将双打放入字符串和整数之间的映射!

我们无法使用正确的参数化类型执行此操作:

Map<Double, Double> other = new HashMap<Double, Double>();
other.put(42.0, 42.0);

Map<String, Integer> map = new HashMap<String, Integer>(other);  // error
Run Code Online (Sandbox Code Playgroud)