Discussion
What will be the output of the program?
import java.util.*;
public class Demo61
{
static class Key
{
StringBuilder id;
Key(String s) { id = new StringBuilder(s); }
public boolean equals(Object o)
{
return o instanceof Key && (
(Key) o).id.toString().equals(id.toString());
}
public int hashCode() { return id.toString().hashCode(); }
}
public static void main(String[] args)
{
Set<Key> set = new HashSet<Key>();
Key k = new Key("a");
set.add(k);
k.id.append("b");
System.out.println(set.contains(k) + " " + set.size());
}
}
Answer: A
The key was filed under the hash of a, and mutating it afterwards changes the hash to that of ab, so the lookup searches the wrong bucket and reports false. The element is still in the set, so the size is 1: it has become unreachable rather than removed. Anything used as a hash key must be effectively immutable.
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