There is a reason for this behaviour. Let us figure it out in a reverse way.
Let's assume it works (later we will see the ill effects and hence will conclude why it was decided to make it non compiling)
public class Some{
private Map < Object, Object > map;
public class setMap(Map < Object,Object > map){
this.map = map;//considering it was allowed and implicit casting was done.
this.map.add(1,2);
this.map.add(new Student(), new Object());
this.map.add("abcd", new Student());
this.map.add(new Employee(), new House());
this.map.add(new Whatever(), new EveryThing());
// In short now map can hold any object as key and value without promoting any compile error.
}
public void setStudentNameMap(){
setMap(new HashMap < String, Student >());
// What key value pairs now we expect to be of type while iterating ?
}
}
In the code above we intent the map to hold key as of type String and value to be of type Student object and hence we went for using generics and provided the type. But does it helped us ? No even we provided the type still later object of any type can be set as key and value which just defies the use of generics.
Just imagine now iterating the map in the method setStudentNameMap()
. What would be the type expected for key and value ? String and Student for key and value respectively. But what will we get is first object of type Integer as key and value and so on blowing our application with type cast exceptions
Similar is the reason as why its unsafe to mix non generic collections and maps with generic ones.
As we have seen how useless this would have made generics hence it was decided (as one of the main reason) to make it a compile time error