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

Discussion

What will be the output of the program?

import java.util.*;

public class Program100
{
    public static void main(String[] args)
    {
        Map<String, Integer> m = new HashMap<String, Integer>();
        String key = new String("k");
        m.put(key, 1);
        System.out.println(m.get("k") + " " + m.get(new String("k")));
    }
}

  • A.The program prints null null
  • B.The program prints null 1
  • C.The program prints 1 null
  • D.The program prints 1 1

Answer: D

HashMap finds a key with hashCode and equals, never with reference identity, and String implements both by value. Every one of these three String objects therefore agrees, so both lookups return 1. This is exactly why a mutable key, or one without those methods, breaks lookups.

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

Post your comment

Please log in or register to post a comment.