Discussion
What will be the output of the program?
import java.util.*;
public class Trial09
{
static class Point
{
int x;
Point(int x) { this.x = x; }
public boolean equals(Object o)
{
return o instanceof Point && ((Point) o).x == x;
}
}
public static void main(String[] args)
{
Set<Point> s = new HashSet<Point>();
s.add(new Point(1));
s.add(new Point(1));
System.out.println(s.size());
}
}
Answer: A
Point overrides equals but not hashCode, so two equal points almost certainly land in different buckets and the set never compares them. Both are stored and the size is 2. Overriding equals without hashCode breaks every hash-based collection in exactly this way.
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