Discussion
What will be the output of the program?
import java.util.*;
public class Demo96
{
static class Box
{
int v;
Box(int v) { this.v = v; }
public boolean equals(Object o)
{
return o instanceof Box && ((Box) o).v == v;
}
public int hashCode() { return 1; }
}
public static void main(String[] args)
{
Set<Box> s = new HashSet<Box>();
s.add(new Box(1));
s.add(new Box(2));
System.out.println(s.size() + " " + s.contains(new Box(2)));
}
}
Answer: D
A constant hashCode is legal: the contract only requires equal objects to share a hash, not unequal ones to differ. Both boxes land in the same bucket, where equals separates them, so the size is 2 and the lookup succeeds. The cost is performance, since the bucket degenerates into a linear scan.
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