This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Just want to confirm that shoudn't the Compiler stop us when we were putting int values in map where it was expecting String.
How will compiler know what type of key-value pair you store in a raw Map? Generics gives you type-safety. But you can always widen a typed class to a raw type class. In that case you loose the type-safety. To work around this, compiler just adds a typecheck at runtime when you retrieve data from a typed map/collection. And that is giving the cast exception in this case.
Mixing generic code to non-generic code. populate method overlooks at the type safe Map and adds Integer object to the map (Autoboxing is there). Now come back to main method, there is cast (String)map.get(1)+(String)sam.get(1) to get the concatenated String to be printed. But what is got back from the Map are Integer objects, casting Integer to String causes well known ClassCastException.
Joined: Feb 28, 2007
Abheshek: Just want to confirm that shoudn't the Compiler stop us when we were putting int values in map where it was expecting String.
What is passed to the populate() method is just a plain Map, non-type safe Map, that asks for <Object,Object>. There is no information regarding type safety of the Map that is defined in the main method as Map<Integer,String>.
So simply int is boxed to Integer wrapper and added to the map.
Joined: May 10, 2007
Hi Chandra, THANKS a lot.Your all posts are really very helpful.My doubt is cleared. You and Manfred really champions.