Please help understand why
Map map1 = new HashMap<String,String>(); // This compiles
Map<Object,Object> map2 = new HashMap<String,String>(); // This does not.
As per my understanding
Map map1
is same as
Map<Object,Object> map1
---- Edit ----
When generics are not provided for reference map1 , compiler accepts the object creation with any generics. This to me seemed like map1 have implicit
<Object,Object>
generics applied.
So the question here is why compilation fails when map2 have explicit
<Object,Object>
generics applied.
For downvoters , the question for which this is marked as duplicate , does not answer my question directly.
Thanks Chetan and Pham , That explains!!!.
No. A
Map
is not the same as aMap<Object,Object>
.A reference of type
HashMap<T,T>
is a subtype of a reference of typeMap
. In other words, a reference of typeMap
can refer to an object of typeHashMap<String,String>
.On the other hand, a reference of type
HashMap<T,T>
is not a subtype of a reference of typeMap<E,E>
(Even ifT
is-aE
andHashMap
is-aMap
). In other words, a reference of typeMap<Object,Object>
can't refer to an object of typeHashMap<String,String>
even ifString
is-aObject
andHashMap
is-aMap
.If you are wondering why the rules for reference sub types in case of generics works this way, there is one explanation I can give based on my understanding. Generics are syntactic sugar and go through what is known as
type-erasure
once the code is compiled. That is, aHashMap<String,String>
when compiled becomes aHashMap
.If the compiler allowed the statement
Map<Object,Object> map = new HashMap<String,String>
, it would mislead programmers to believe that theMap
can only holdString
key and values at runtime. This would be absurd since Generics go throughtype-erasure
at compile time itself.The statement
Map map = new HashMap<String,String>
is allowed on the other hand mostly for backward compatibility with legacy code.