日期:2014-05-20  浏览次数:20615 次

hey!那位大哥进来帮我看一下。
能不能说说hashcode方法和equal方法的关系。并帮忙看看这道题。我也到网络上查过了,不过这道题还是不确定选哪个?
Comment if the following code implements hashCode() method of Object class correctly? Select the most appropriate answer.

1. public class CorrectHashCode
2. {
3. private int number;
4.
5. public CorrectHashCode(int i)
6. {
7. number = i;
8. }
9.
10. public int hashCode()
11. {
12. int i = (int)(Math.random() * 100);
13. return i * number;
14. }
15.
16. // other methods
17. }
(Choose One)
A. The code implements hashCode() method correctly
B. The code does not implement hashCode() method correctly
C. This implementation of hashCode() method is correct if only if the equals() method is not overridden
D. The given code does not contain enough information to comment on the correctness of the hashCode() method implementation
E. None of these

------解决方案--------------------
重写hashcode()还有这么多规矩?我选A,还是说怕那个number没来得及初始化hashcode就被调用了
------解决方案--------------------
程序中真正的hashcode是和内存地址有关的,所以你可以想象每个对象的hashcode是不可能相同的,两个不一样的对象不能同时在一个内存地址上,这个肯定确保了不同对象的hashcod不同。
但是在实际运行中我们判断对象是否相同不需要那么严格,两个字符串内容一样我们就认为是相等了,而不去看他是不是在同一个内存地址上,所以这个时候我们就要重新写这个equals来达到当内容相同就返回true了,而不去管内存地址是不是一样了

当equals方法被重写时,通常有必要重写 hashCode 方法,以维护 hashCode 方法的常规协定,该协定声明相等对象必须具有相等的哈希码
常规协定就是:
hashCode 的常规协定是: 

在 Java 应用程序执行期间,在对同一对象多次调用 hashCode 方法时,必须一致地返回相同的整数,前提是将对象进行 equals 比较时所用的信息没有被修改。从某一应用程序的一次执行到同一应用程序的另一次执行,该整数无需保持一致。 
如果根据 equals(Object) 方法,两个对象是相等的,那么对这两个对象中的每个对象调用 hashCode 方法都必须生成相同的整数结果。 
如果根据 equals(java.lang.Object) 方法,两个对象不相等,那么对这两个对象中的任一对象上调用 hashCode 方法不 要求一定生成不同的整数结果。但是,程序员应该意识到,为不相等的对象生成不同整数结果可以提高哈希表的性能