Originally posted by Rekha:
My doubt is: We have declared the generic type of the Maps to be Map<Integer,String>. Then, why does not the compiler err while compiling Line 1 where we are putting an int in a place where String is expected? (Because we have defined the Generic types to state that the Key is of type Integer and Value is of type String)
Well Rekha, first of all you need to remember that generics are a compile time check.
so if you say,
The compiler will ensure that you put key/value pair in *map* and *sap* which is of type Integer/String. After it has ensured that, it will remove the type info and your above two declarations would look like:
i.e. normal Maps to the jvm at runtime.
Now, if you declare
static void pop(Map m) then you are declaring a Map raw type as an argument to the method pop. The compiler knows that it(Map m) can hold all Objects,..... right.
Hence it allows you to put int's into the Map by autoboxing them into Integers.
Therefore, when you try to retrieve the value of the Map's using get() method, the jvm throws ClassCastException as it got an Integer instead of a String.
So, it's a classical case of mixing generic type code with non-generic type code which the developer should avoid or be careful not to blow it up!!!
Hope this makes sense!

[ November 30, 2008: Message edited by: Harvinder Thakur ]