首先我们来看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();
1.同一个对象的hashcode每次都应该返回相同的值
2.如果equals方法相同,则hashcode也要相同
3.equals不同,hashcode一定要不同,但是尽量给不同的对象不同的hashcode,可以提高hashtable类似的效率。
首先针对第三点,因为hashMap中都是先按照hashcode来定位在数组的哪一个Entry的,如果不同的对象的Hashcode相同,就会产生hash碰撞,效率就会低下,所以建议不同的对象不同的hashcode值。
再来解释为什么第二条要求重写equals方法要重写hashcode方法。因为按照equals比较逻辑相同的对象,应该可以取到值,但是如果hashcode不同,就不能取到相同的值。
例如下面的例子
public class User {
private Integer age;
private String name;
public User(Integer age, String name) {
this.age = age;
this.name = name;
}
@Override
public boolean equals(Object obj) {
if(obj == this)
return true;
if(! (obj instanceof User))
return false;
User user = (User) obj;
return (name.equals(user.name) && age.equals(user.age));
}
public static void main(String[] args) {
Map<User, String> map = new HashMap<>();
map.put(new User(12, "aa"), "Hello World");
System.out.println(map.get(new User(12, "aa")));
}
}
按道理来说,我们通过定义equals方法相同,那么逻辑上来说应该第二次能取到Hello World,但是没有取到,因为还是先拿我们的Key去取hashcode进行取模,因为我们只重写了equals方法,而没有重写hashcode方法,导致两次定位的数组中的位置不一致,所以第二次取不到,如果重写了hashcode方法就可以取到了。
public class User {
private Integer age;
private String name;
public User(Integer age, String name) {
this.age = age;
this.name = name;
}
@Override
public boolean equals(Object obj) {
if(obj == this)
return true;
if(! (obj instanceof User))
return false;
User user = (User) obj;
return (name.equals(user.name) && age.equals(user.age));
}
@Override
public int hashCode() {
return Objects.hash(age, name);
}
public static void main(String[] args) {
Map<User, String> map = new HashMap<>();
map.put(new User(12, "aa"), "Hello World");
System.out.println(map.get(new User(12, "aa")));
}
}
重写了hashcode方法后就可以取到了。
看看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);
}