【转载】hashCode()、equals()以及compareTo()方法的理解
判断两个对象是否相等(是同一个对象),首先调用hashCode()方法得到各自的hashcode,
1、如果hashcode不相等,则表明两个对象不相等。
2、如果hashcode相等,继续调用equals方法进行判断
2.1:equals()返回true,则对象相等
2.2:equals()返回fasle,两对象不相等
所以,要求程序员在重写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中可以看出:
重写compareTo()方法,不要求必须重写equals()方法,但是却强烈推荐重写equals(),以使两个方法的比较结果在逻辑上是一致。原话如下:
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.
所以在编写需要用TreeSet添加的对象时,该对象一定要实现Comparable接口,并且重写compareTo()方法,并推荐同时重写equals()方法
原文出自:http://blog.sina.com.cn/s/blog_50d936c40100nvzz.html