【发布时间】:2014-02-05 21:18:46
【问题描述】:
我正在准备java认证,显然我无法正确回答这个答案。
给定:
2. class Chilis {
3. Chilis(String c, int h) { color = c; hotness = h; }
4. String color;
5. private int hotness;
6. public boolean equals(Object o) {
7. Chilis c = (Chilis)o;
8. if(color.equals(c.color) && (hotness == c.hotness)) return true;
9. return false;
10. }
11. // insert code here
12. }
在第 11 行独立插入,满足 equals() 和 辣椒的 hashCode() 合约? (选择所有适用的。)
- A. public int hashCode() { return 7; }
- 乙。 public int hashCode() { 返回热度; }
- C. public int hashCode() { return color.length(); }
- D. public int hashCode() { return (int)(Math.random() * 200); }
- E. public int hashCode() { return (color.length() + hotness); }
书上说:
A, B, C, and E are correct. They all guarantee that two objects that equals() says are
equal, will return the same integer from hashCode(). The fact that hotness is private
has no bearing on the legality or effectiveness of the hashCode() method.
现在我得到了正确的 A 和 B,但不是 C 和 E,因为这对我来说听起来不正确。看下面的例子:
Under c = new Under("ciao", 9);
Map<Under, String> map = new HashMap<Under, String>();
map.put(c, "ciao");
System.out.println(map.get(c));
c.color = "uauauauauau";
System.out.println(map.get(c));
输出将是:
ciao
null
我说的是基于颜色的访问修饰符。在 Object 类的文档中,我们有合同:
- 只要在 Java 应用程序执行期间对同一个对象多次调用,hashCode 方法必须始终返回相同的整数,前提是没有修改对象上的 equals 比较中使用的信息。该整数不需要在应用程序的一次执行与同一应用程序的另一次执行之间保持一致。
- 如果两个对象根据 equals(Object) 方法相等,则对两个对象中的每一个调用 hashCode 方法必须产生相同的整数结果。
- 如果根据 equals(java.lang.Object) 方法,如果两个对象不相等,则不要求对两个对象中的每一个调用 hashCode 方法必须产生不同的整数结果。但是,程序员应该意识到,为不相等的对象生成不同的整数结果可能会提高哈希表的性能。
那么根据这些规则中的第一条,是否应该期望它具有这种行为?
【问题讨论】: