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")));
}
}
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.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development