hashCode()方法
首先来看看hashCode()在源代码中的注释(java8):
/**
* 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();
作用是:为对象返回一个hash值,为支持哈希表提供了很好的支持。
hashCode的约定是:
- 在一个java程序执行期间,如果对象中用于等价比较的信息没有改变,同一个对象无论何时超过一次执行,该方法都返回相同的整数。这个哈希值在程序的一个执行到该程序的另一个执行不需要保持一致。
- 如果两个对象通过equals()判断为相等的,那么调用两个对象的hashCode()肯定也返回相同的值。
- 通过equals()方法判断不相等的两个对象的hash值并不意味是不同的。但是程序员要意识到不同对象产生不同的哈希值有助于提高哈希表的性能。
最佳实践是类中定义的hashCode方法,不同的对象返回不同的值。(通常的实现是将对象的内部地址转换为一个值,但是这个技术实现不是java变成语言所必须的)
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);
}
- 自反性:对于任意非空引用x,x.equals(x)一定返回true
- 对称性:对于任意非空引用x,y,如果x.equals(y)返回true,那么y.equals(x)也一定返回true
- 传递性:对于任意非空引用x,y,z,如果x.equals(y)返回true和y.equals(z)返回true,那么x.equals(z)也一定返回true
- 一致性:对于任意非空引用x,y,如果对象中用于等价比较的信息没有改变,那么无论调用多少次x.equals(y)返回的结果都是一致的,要么是true,要么是false
- 对任何不是null的x,x.equals(null)一定返回false
Object类的equals()方法实现的是最挑剔的可能等价的关系。也就是说,对于任何非空引用x,y,当且仅当x,y引用于同一个对象才会返回true
需要注意的是,当该方法被重写时通常需要重写hashCode()方法,符合hashCode()方法的约定,即平等对象必须有相同的哈希码
为什么通常重写equals还要重写hashCode()的方法,因为在java集合类有关散列表的实现中,通常不仅仅判断equals方法,还会判断hashCode()方法
public class User {
private String name;
private int age;
public User(){}
public User(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
if (age != user.age) return false;
return name != null ? name.equals(user.name) : user.name == null;
}
public static void main(String[] args) {
Map<User,String> map = new HashMap<>();
map.put(new User("a",1),"1");
System.out.println(map.get(new User("a",1)));
}
只重写equals方法后,输出为null,主要原因在于HashMap的判断方法同时判断hash值和equals(),
而一般默认Object的hashCode()方法是映射于对象的存储地址。
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//判断
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
//判断
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
也重写hashCode方法:
public class User {
private String name;
private int age;
public User(){}
public User(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
if (age != user.age) return false;
return name != null ? name.equals(user.name) : user.name == null;
}
@Override
public int hashCode() {
return name.hashCode()*37+age;
}
public static void main(String[] args) {
Map<User,String> map = new HashMap<>();
map.put(new User("a",1),"1");
System.out.println(map.get(new User("a",1)));
}
}
输出的为1,是正确的