This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help understanding a generics and collections question

 
L K Kakani
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • 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.
 
Piotr Nowicki
Ranch Hand
Posts: 611
1
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
  • 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
  • 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: 611
1
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's what I think :-)

No problem mate!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic