在object类中,hashcode()方法是本地方法,返回的是对象的地址值,而object类中的equals()方法比较的也是两个对象的地址 值,如果equals()相等,说明两个对象地址值也相等,当然hashcode()也就相等了。一旦一个类重写equals()方法,通常也会重写 hashCode()方法。
2.java判断两个对象是否相等的规则
首先,判断两个对象的hashCode是否相等;
如果不相等,认为两个对象也不相等;
如果相等,则判断两个对象用equals运算是否相等;
如果不相等,认为两个对象也不相等;
如果相等,认为两个对象相等。
当我们重写了一个类的equals()方法后,我们一定要记住同时也要重写hashCode()方法。
下面介绍如何来重写hashCode()方法。通常重写hashCode()方法按以下设计原则实现。
(1)把某个非零素数,例如17,保存在int型变量result中。
(2)对于对象中每一个关键域f(指equals方法中考虑的每一个域)参照以下原则处理。
boolean型,计算(f?0:1)。
byte、char和short型,计算(int)f。
long型,计算(int)(f^(f>>32))。
float型,计算Float.floatToIntBits(f)。
double型,计算Double.doubleToLongBits(f)得到一个long,再执行long型的处理。
对象引用,递归调用它的hashCode()方法。
数组域,对其中的每个元素调用它的hashCode()方法。
(3)将上面计算得到的散列码保存到int型变量c,然后执行result = 37 * result + c。
(4)返回result。
3.String的hashcode方法
/**
* Returns a hash code for this string. The hash code for a
* <code>String</code> object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using <code>int</code> arithmetic, where <code>s[i]</code> is the
* <i>i</i>th character of the string, <code>n</code> is the length of
* the string, and <code>^</code> indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/
public int hashCode() {
int h = hash;
int len = count;
if (h == 0 && len > 0) {
int off = offset;
char val[] = value;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
4.String的equals方法
/**
* Compares this string to the specified object. The result is {@code
* true} if and only if the argument is not {@code null} and is a {@code
* String} object that represents the same sequence of characters as this
* object.
*
* @param anObject
* The object to compare this {@code String} against
*
* @return {@code true} if the given object represents a {@code String}
* equivalent to this string, {@code false} otherwise
*
* @see #compareTo(String)
* @see #equalsIgnoreCase(String)
*/
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}