my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes MasterExam question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "MasterExam question" Watch "MasterExam question" New topic

MasterExam question

Felix Tang

Joined: Aug 15, 2006
Posts: 7
Hi, this is a question from one of the MasterExams from the K & B CD-ROM.

import java.util.*;
public class Mangler
public static <K,V> Map <V,K> mangle(Map <K,V> in){
Map <V,K> out = new HashMap <V,K>();
for (Map.entry<K,V> entry: in.entrySet())
out.put(entry.getValue(), entry.getKey());
return out;

public static void main(String[] args)
Map m1 = new HashMap();
m1.put("a", 1);
m1.put("b", 2);
Map m2 = mangle(m1);
System.out.println(m2.get("a") + "" + m2.get(2));

The answer is "null b". I read the explanation but I still don't understand why. And why does entry.getValue() belong to type <V> and entry.getKey() belong to type <K>?

Any help would be appreciated
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
The entry method is defined as "Set<Map.Entry<K,V>> entrySet()"; Here is API for the interface Map.Entry<K,V>:
I agree. Here's the link:
subject: MasterExam question
It's not a secret anymore!