以JDK1.8源码详解。
一、Object类的hashcode和equals方法
equals方法源码:
/**
* Indicates whether some other object is "equal to" this one.
* <p>
* The {@code equals} method implements an equivalence relation
* on non-null object references:
* <ul>
* <li>It is <i>reflexive</i>: for any non-null reference value
* {@code x}, {@code x.equals(x)} should return
* {@code true}.
* <li>It is <i>symmetric</i>: for any non-null reference values
* {@code x} and {@code y}, {@code x.equals(y)}
* should return {@code true} if and only if
* {@code y.equals(x)} returns {@code true}.
* <li>It is <i>transitive</i>: for any non-null reference values
* {@code x}, {@code y}, and {@code z}, if
* {@code x.equals(y)} returns {@code true} and
* {@code y.equals(z)} returns {@code true}, then
* {@code x.equals(z)} should return {@code true}.
* <li>It is <i>consistent</i>: for any non-null reference values
* {@code x} and {@code y}, multiple invocations of
* {@code x.equals(y)} consistently return {@code true}
* or consistently return {@code false}, provided no
* information used in {@code equals} comparisons on the
* objects is modified.
* <li>For any non-null reference value {@code x},
* {@code x.equals(null)} should return {@code false}.
* </ul>
* <p>
* The {@code equals} method for class {@code Object} implements
* the most discriminating possible equivalence relation on objects;
* that is, for any non-null reference values {@code x} and
* {@code y}, this method returns {@code true} if and only
* if {@code x} and {@code y} refer to the same object
* ({@code x == y} has the value {@code true}).
* <p>
* Note that it is generally necessary to override the {@code hashCode}
* method whenever this method is overridden, so as to maintain the
* general contract for the {@code hashCode} method, which states
* that equal objects must have equal hash codes.
*
* @param obj the reference object with which to compare.
* @return {@code true} if this object is the same as the obj
* argument; {@code false} otherwise.
* @see #hashCode()
* @see java.util.HashMap
*/
public boolean equals(Object obj) {
return (this == obj);
}
该equals方法,是一个非空对象引用集合上的等价关系,满足下面几点:
1、反身性(reflexive)
对于任意的非空引用x,也就是说x不等于null,有x.equals(x)总是返回true。
2、对称性(symmetric)
对于任意的非空引用x和y,有x.equals(y)返回true当且仅当y.equals(x)返回true。
3、传递性(transitive)
对于任意的非空引用x、y和z,如果x.equals(y)返回true且y.equals(z)返回true,那么x.equals(z)返回true。
4、一致性(consistent)
对于任意的非空引用x和y,如果用于equals比较的对象没有被修改的话,那么,对此调用x.equals(y)要么一致地返回true,要么一致的返回false。
5、非空性(null)
对于任意的非空引用x,x.equals(null)总是返回false。
hashcode方法源码:
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hash tables such as those provided by
* {@link java.util.HashMap}.
* <p>
* The general contract of {@code hashCode} is:
* <ul>
* <li>Whenever it is invoked on the same object more than once during
* an execution of a Java application, the {@code hashCode} method
* must consistently return the same integer, provided no information
* used in {@code 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.
* <li>If two objects are equal according to the {@code equals(Object)}
* method, then calling the {@code hashCode} method on each of
* the two objects must produce the same integer result.
* <li>It is <em>not</em> required that if two objects are unequal
* according to the {@link java.lang.Object#equals(java.lang.Object)}
* method, then calling the {@code 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.
* </ul>
* <p>
* As much as is reasonably practical, the hashCode method defined by
* class {@code Object} does return distinct integers for distinct
* objects. (This is typically implemented by converting the internal
* address of the object into an integer, but this implementation
* technique is not required by the
* Java™ programming language.)
*
* @return a hash code value for this object.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.System#identityHashCode
*/
public native int hashCode();
JDK1.8中hashcode的源码不可见。但能看到hashcode以下几点约定:
1、在程序的一次执行过程中,对同一个对象调用hashcode必须一致地返回同一个整数。在同一个程序执行两次中hashcode产生的整数不必要保持一致。
2、根据equals(Object)方法计算的两个对象是相等的,那么两个对象调用hashcode方法会产生相同的整数。
3、根据equals(Object)方法计算的两个对象不相等,那么两个对象调用hashcode方法也有可能产生相同的整数,如果产生的整数不同,将会改善哈希表的性能。
注意:hashCode返回的并不一定是对象的(虚拟)内存地址,具体取决于运行时库和JVM的具体实现。
二、为什么要重写equals方法
先看一段未重写equals方法的代码:
package com.leboop;
public class EqualsTest {
public static void main(String[] args) {
Person p1 = new Person("zhangsan",23);
Person p2 = new Person("zhangsan",23);
//输出false
System.out.println(p1.equals(p2));
}
}
package com.leboop;
public class Person {
private String name;
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
主程序中两个Person实例,按照实际情况具有相同姓名和年龄(仅考虑姓名和年龄)应该是同一个人,而程序判断不是同一个人,这是因为Java中所有的类都继承自Object,当然自定义的Person类也不例外。所以p1.equals(p2)调用的是父类Object中equals方法,当然不是同一各对象。我们如下重写equals方法:
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age == null) {
if (other.age != null)
return false;
} else if (!age.equals(other.age))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
重写的equals方法判断的基本逻辑如下:
(1)如果比较的两个对象是同一个对象(指引用地址相同),直接返回true;
(2)如果被比较的对象是null,返回false;
(3)如果两个对象所属的类不相同,直接返回false;
(4)当前面的条件都不满足时,将被比较对象转换成Person对象,然后对姓名和年龄进行比较,如果两者均相等时,返回true,否则返回false;
所以程序将会输出true。
三、为什么要重写hashcode方法
假设如前面已经重写了equals方法,但是没有重写hashcode方法,看如下一段代码:
package com.leboop;
public class Person {
private String name;
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age == null) {
if (other.age != null)
return false;
} else if (!age.equals(other.age))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
package com.leboop;
public class HashCodeTest {
public static void main(String[] args) {
Person p1 = new Person("zhangsan",23);
Person p2 = new Person("zhangsan",23);
//输出false
System.out.println(p1.hashCode()==p2.hashCode());
}
}
程序会输出false,认为两个相等的对象hashcode不相等,这与hashcode方法的约定是矛盾的。所以我们如下重写hashcode方法:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
重写执行程序将输出true。