• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Help understanding a generics and collections question

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is one of the questions from the SCJP6 book mock exam A




Why is the answer "null b" ? In the explanation it was given that because Map m2 is not typed we get null accessing m2.get("a") but b for m2.get(2). Why not null for both?

Thanks

Kakani.
 
Ranch Hand
Posts: 623
1
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The mangle method is returning a new map which switch the key with value. In other words, it converts (String => Integer) mapping into (Integer => String).

The m2 map is something like:

1 => "a"
2 => "b"

That's why m2.get("a") returns null (there is no such key in the map) and m2.get(2) returns "b" as it's the actual value for this key.

The generic code would look like this:



and the result remains unchanged.
 
L K Kakani
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot Pedro. So it has got nothing to do with the type of Map m2 it's just because of using a value in get() method instead of key.
 
Piotr Nowicki
Ranch Hand
Posts: 623
1
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That's what I think :-)

No problem mate!
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic