This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Help understanding a generics and collections question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Help understanding a generics and collections question" Watch "Help understanding a generics and collections question" New topic
Author

Help understanding a generics and collections question

L K Kakani
Ranch Hand

Joined: Aug 30, 2010
Posts: 32
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.


SCJP 6.0(88%)
Piotr Nowicki
Ranch Hand

Joined: Jul 13, 2010
Posts: 610

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.


OCP Java SE 6 Programmer, OCM Java SE 6 Developer, OCE Java EE 6 JSPSD, OCE Java EE 6 EJBD, OCE Java EE 6 JPAD, Spring 3.0 Core Professional.
L K Kakani
Ranch Hand

Joined: Aug 30, 2010
Posts: 32
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

Joined: Jul 13, 2010
Posts: 610

That's what I think :-)

No problem mate!
 
 
subject: Help understanding a generics and collections question