• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

MasterExam question

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
You firghten me terribly. I would like to go home now. Here, take this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic