Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

map question from practice exam

 
Rachel Glenn
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the sample code:



I understand that the call to m2.get("a") returns NULL and the call to m2.get(2) returns "b".

I am surprised it is even allowed to compile. The answer says a warning is generated, but I guess the compiler sees that since a raw map is being passed in, that all type info is lost in the actual mangle function?
 
Greg Charles
Sheriff
Posts: 2985
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see obvious compile errors at lines 5,6, and 11. Line 11 is an obvious typo, but I'm less sure what you're going for on lines 5 and 6.

The thing to remember about generics is they are a compile time concept. If you use a raw type, the compiler will warn you, but won't error out. The runtime won't even care ... at least, not until you try to use an object as a type it's not.
 
Rachel Glenn
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greg Charles wrote:I see obvious compile errors at lines 5,6, and 11. Line 11 is an obvious typo, but I'm less sure what you're going for on lines 5 and 6.

The thing to remember about generics is they are a compile time concept. If you use a raw type, the compiler will warn you, but won't error out. The runtime won't even care ... at least, not until you try to use an object as a type it's not.


yes I do have some typos...but I see what you are saying. Your response made things clear for me in that if we do use the typed collections (as in Map<T>), the compiler will do type checking for us and issue errors if needed. But if we do NOT use the typed collections, but rather untyped version, like a plain old Map, then the most the compiler can do is issue warnings.
 
Himai Minh
Ranch Hand
Posts: 1296
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let me type up the code :

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic