请教考题:用对象作为map键时,重写equals和hashcode方法的问题
有这样一道考题:
Given:
2. class Chilis {
3. Chilis(String c, int h) { color = c; hotness = h; }
4. String color;
5. int hotness;
6. public boolean equals(Object o) {
7. if(this == (Chilis)o) return true;
8. return false;
9. }
10. public String toString() { return color + " " + hotness; }
11. }
If instances of class Chilis are to be used as keys in a Map, which are true? (Choose all that
apply.)
A. Without overriding hashCode(), the code will not compile.
B. As it stands, the equals() method has been legally overridden.
C. It’s possible for such keys to find the correct entries in the Map.
D. It’s NOT possible for such keys to find the correct entries in the Map.
E. As it stands, the Chilis class legally supports the equals() and hashCode() contracts.
F. If hashCode() was correctly overridden, it would make retrieving Map entries by key easier.
正确答案是:B C E
它为什么不选F呢?
首先它没有重写hashCode(),我以为重写hashcode()会提高搜索速度,相当于给对象加了个主键,只按主键搜索,而不是一个一个对象去搜索,不是这样么?请高手指点迷津
而且equals()的重写也没有起到真正的作用,只要2个Chillis对象比较,统统返回true。