hashCode()、equals()以及compareTo()方法的理解
1、如果hashcode不相等,则表明两个对象不相等。
2、如果hashcode相等,继续调用equals方法进行判断
所以,要求程序员在重写hashCode方法时尽量做到:不一样的对象,hashCode不一样,这样在判断两个对象是否是同一对象时可以提高效率。
根据这两点,我们可以看一道常见的JAVA面试题:
题目:对于两个对象A、B,A.equals(B)==true,不一定有相同的hashCode(); 这句话是错误的。
当然你自己定义的对象可以实现equals相同而hashCode不同(并不会报错,不知道JAVA为什么不限死),但java的Object类中规定相同的对象一定要有相同的hashCode:原话如下:
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
compareTo()方法和equals()方法的关系:
对于某些对象如集合(TreeSet)需要实现内部排序,所以要实现Comparable接口,从而要实现里面的唯一方法compareTo();实现Comparable接口的对象表明遵循自然排序。从Comparable的API中可以看出:
It is strongly recommended (though not required) that natural orderings be consistent with equals. This is so because sorted sets (and sorted maps) without explicit comparators behave "strangely" when they are used with elements (or keys) whose natural ordering is inconsistent with equals. In particular, such a sorted set (or sorted map) violates the general contract for set (or map), which is defined in terms of the equals method.