• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

MasterExam question

 
Felix Tang
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2023
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic