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

Discussion

What will be the output of the program?

import java.util.*;

public class Listing63
{
    public static void main(String[] args)
    {
        Map<String, List<String>> m = new HashMap<String, List<String>>();
        List<String> shared = new ArrayList<String>();
        m.put("x", shared);
        m.put("y", shared);
        m.get("x").add("v");
        System.out.println(m.get("y").size() + " " + m.size());
    }
}

  • A.The program prints 0 1
  • B.The program prints 0 2
  • C.The program prints 1 2
  • D.The program prints 1 1

Answer: C

Both keys were given the SAME list object, so appending through one key is visible through the other and the size reads 1. The map itself holds two entries because the keys differ. Storing a value twice stores the reference twice, never a copy.

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

Post your comment

Please log in or register to post a comment.