Java – what is the difference between these generic statements?

See the English answer > is this raw type assignment type safe? List
= new ArrayList(); 1

Map<String,Integer> map = new HashMap<String,Integer>();

and

Map<String,Integer> map = new HashMap();

Since this is new to me, I'm not sure what the actual difference between the two statements is, because both seem to work well I tried to find it elsewhere, but I couldn't find any specific answer

Solution

The second variant uses raw type, which is usually bad In fact, primitive types exist only for backward compatibility reasons

Think about it:

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

Map<String,Integer> map = new HashMap(other);

Using primitive types, we try to put doubles into the mapping between strings and integers!

We cannot perform this operation with the correct parameterized type:

Map<Double,Integer>(other);  // error
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>