wood burning stoves 2.0*
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


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 "MasterExam question" Watch "MasterExam question" New topic
Author

MasterExam question

Felix Tang
Greenhorn

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>:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.Entry.html
 
Consider Paul's rocket mass heater.
 
subject: MasterExam question