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

Discussion

What will be the output of the program?

import java.util.*;

public class Example88
{
    public static void main(String[] args)
    {
        Map<Integer, String> m = new HashMap<Integer, String>();
        for (int i = 0; i < 3; i++) m.put(i, "v" + i);
        m.remove(1);
        System.out.println(m.containsKey(1) + " " + m.size() + " " + m.get(1));
    }
}

  • A.The program prints false 3 null
  • B.The program prints true 2 v1
  • C.The program prints true 3 v1
  • D.The program prints false 2 null

Answer: D

Correct answer: The program prints false 2 null

The loop puts keys 0, 1 and 2, and remove(1) takes one out. So containsKey(1) is false, the size is 2, and get(1) returns null. Note that a null from get is ambiguous on its own - it means either absent or mapped to null - which is exactly why containsKey exists as a separate method.

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

Post your comment

Please log in or register to post a comment.