Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

import java.util.*;

public class Fragment18
{
    static String lookup(Map<Integer, String> m, Object key)
    {
        return m.get(key);
    }

    public static void main(String[] args)
    {
        Map<Integer, String> ids = new HashMap<Integer, String>();
        ids.put(7, "seven");
        System.out.println(lookup(ids, 7) + " " + lookup(ids, 7L));
    }
}

  • A.The program prints seven seven
  • B.The program prints seven null
  • C.The program prints null null
  • D.Compilation fails.

Answer: B

The key was stored as an Integer. Looking up 7 boxes to an Integer and matches, but 7L boxes to a Long, and Long.equals(Integer) is false whatever the numeric value, so the second lookup misses and returns null. Map.get accepts any Object, so nothing warns you at compile time.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.