前言
本文介绍在Java中如何重写equals和hashcode方法。结合一些案例来深入分析背后的实现原理。后面会持续更新相关系列文章,欢迎朋友们一同分享与探讨!
可能大家会被经常问到为什么重写equals和hashcode? 相信大家和我一样被这问题困扰了很久,首先我们知道equals和hashcode同为Object方法,默认的equals方法是Object方法,比较的是对象的内存地址
/**
* 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);
}
而hashcode为本地方法,而默认的hashcode是调用native方法根据这个对象在内存中的实际地址值来算的一个哈希码值
/**
* 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();
结合案例来验证分析:
public class HashCodeEqualsRewrite {
static class UserInfo{
private String userName;
private Integer age;
//getset()....
}
public static void main(String[] args) {
UserInfo userInfo1 = new UserInfo();
userInfo1.setUserName("admin");
userInfo1.setAge(18);
UserInfo userInfo2 = new UserInfo();
userInfo2.setUserName("admin");
userInfo2.setAge(18);
System.out.println(userInfo1.equals(userInfo2));//false
//hashcode 不等
System.out.println(userInfo1.hashCode());
System.out.println(userInfo2.hashCode());
}
}
以上为未重写equals和hashcode之前对象之间比较:这里很简单因为equals默认为object类中,比较的是对象的内存地址,所以对象相等比较肯定为false,hashcode一定是不相等的
public class HashCodeEqualsRewrite {
static class UserInfo{
private String userName;
private Integer age;
//getset()....
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserInfo userInfo = (UserInfo) o;
return Objects.equals(userName, userInfo.userName) &&
Objects.equals(age, userInfo.age);
}
@Override
public int hashCode() {
return Objects.hash(userName, age);
}
}
public static void main(String[] args) {
UserInfo userInfo1 = new UserInfo();
userInfo1.setUserName("admin");
userInfo1.setAge(18);
UserInfo userInfo2 = new UserInfo();
userInfo2.setUserName("admin");
userInfo2.setAge(18);
System.out.println(userInfo1.equals(userInfo2));//true
//hashcode 相等
System.out.println(userInfo1.hashCode());
System.out.println(userInfo2.hashCode());
}
}
以上为重写equals和hashcode之后对象之间比较: 同时重写equals和hashcode,对象相等,则hashcode一定相等。
Objects类源码
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
public static int hash(Object... values) {
return Arrays.hashCode(values);
}
Arrays类源码 重写了hashcode,这里采用31散列码计算
public static int hashCode(Object a[]) {
if (a == null)
return 0;
int result = 1;
for (Object element : a)
result = 31 * result + (element == null ? 0 : element.hashCode());
return result;
}
还有一种场景就是重写了equals方法而不重写hashcode方法,由于默认的hashcode方法是根据内存中的实际地址值来算的一个哈希码值,所以两个对象hashcode则不一定相等。但是这种场景不利于哈希表的性能,按照官方的说法就是重写equals时尽可能同时重写hashcode
引用:《Effective java》一书中这样说到:在每个覆盖了 equals() 方法的类中,也必须覆盖 hashCode() 方法,如果不这样做的话,就会违反 Object.hashCode 的通用的约定,从而导致该类无法结合所有基于散列的集合一起正常运作,这样的集合包括HashMap,HashSet 和 HashTable
重写 hashcode() 约定
- 如果两个对象相等,那么两个对象hashcode一定相等;
- 如果两个对象不相等,那么两个对象hashcode一定不相等;
- 如果两个对象hashcode相等,那么两个对象不一定相等;
- 如果两个对象hashcode不相等,那么两个对象一定不相等;
题外话
- Java 中大多类都会重写equals方法,比如String类重写了equal和hashcode方法,equal则比较的为值
- 一般lombok中@Data函数注解在类上, 为类提供读写属性, 此外还提供了 equals()、hashCode()、toString() 方法
以上就是本文的全部内容,希望对大家的学习有所帮助。