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

Discussion

What will be the output of the program?

import java.util.*;

public class Case10
{
    static class Tag
    {
        String name;
        Tag(String name) { this.name = name; }

        public boolean equals(Object o)
        {
            return o instanceof Tag && ((Tag) o).name.equals(name);
        }

        public int hashCode() { return name.hashCode(); }
    }

    public static void main(String[] args)
    {
        Map<Tag, Integer> counts = new HashMap<Tag, Integer>();
        counts.put(new Tag("red"), 1);
        counts.put(new Tag("red"), 2);
        System.out.println(counts.size() + " " + counts.get(new Tag("red")));
    }
}

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

Answer: B

Tag overrides equals AND hashCode consistently, so the second put finds the existing key, replaces its value and leaves one entry. A lookup with a third, equal Tag also succeeds, giving 1 and 2. Without hashCode, as in the previous question, each of these would have been treated as a distinct key.

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

Post your comment

Please log in or register to post a comment.