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.
Please log in or register to report this question.