Java中的hashcode 和 equals

来源:互联网 发布:微信支付接口代码 js 编辑:程序博客网 时间:2024/05/23 20:30

Object 类中equals方法的默认实现为:

public boolean equals(Object obj) {    return (this == obj);}

可以看出内部直接用 == 来比较两个对象是否相等,


equals 方法实现必须满足一下几条规则:自反性、对称性、传递性、一致性、非空性

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true. 
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. 
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. 
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified. 
  • For any non-null reference value x, x.equals(null) should return false.

hashCode
返回一个哈希码,它的作用是确定一个对象在哈希表中的索引位置。所以只有当创建某个类的散列表时,该类的hashCode才有用,其他情况类的hashCode没有作用。散列表如HashMap、HashTable、HashSet。

JDK API文档中对 hashCode重写有个约定:


The general contract of hashCode is: 
  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. 
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. 
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables. 

意思是:1 hashCode 方法返回结果的一致性;2 如果两个对象相等,则它们的hashCode必须要相等;3如果两个对象不相等,则它们的hashCode 方法要返回不同的结果,主要是为了避免哈希冲突。


hashCode 和 equals 的关系
  • 当没有用到散列表时,hashCode和equals没有关系,则有:若两个对象相等,他们的hashCode不一定相等。此种做法可行但是违背了hashCode实现的约定,所以不建议这样做。
  • 当使用了散列表时,hashCode和equals是有关系的,则有:若两个对象相等,那么他们的hashCode一定相等;若两个对象的hashCode相等,那么这两个对象不一定相等。后者发生了哈希冲突,在这种情况下,若要判断两个对象是否相等,hashCode和equals方法都要重写。
                                                                                                 
注意这里的相等都是指,通过equals方法比较两个对象时返回true。

参考文献:
http://www.cnblogs.com/skywang12345/p/3324958.html

http://www.cnblogs.com/Qian123/p/5703507.html

原创粉丝点击