java里中equals, hashCode,toString的作用_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java里中equals, hashCode,toString的作用

java里中equals, hashCode,toString的作用

 2011/12/5 7:34:30  it158  http://it158.iteye.com  我要评论(0)
  • 摘要:对于一般的java值对象或实体对象来说,这三个方法总是应该覆盖的equals,hashCode,toString,所以我总是把值对象从下面这个类继承publicabstractclassBaseObjectimplementsSerializable{/***DOCUMENTME!**@returnDOCUMENTME!*/publicabstractStringtoString();/***DOCUMENTME!**@paramoDOCUMENTME!**@returnDOCUMENTME
  • 标签:has Hash Java

对于一般的java值对象或实体对象来说, 这三个方法总是应该覆盖的
equals, hashCode, toString, 所以我总是把值对象从下面这个类继承

public abstract class BaseObject implements Serializable {
??? /**
???? * DOCUMENT ME!
???? *
???? * @return DOCUMENT ME!
???? */
??? public abstract String toString();

??? /**
???? * DOCUMENT ME!
???? *
???? * @param o DOCUMENT ME!
???? *
???? * @return DOCUMENT ME!
???? */
??? public abstract boolean equals(Object o);

??? /**
???? * DOCUMENT ME!
???? *
???? * @return DOCUMENT ME!
???? */
??? public abstract int hashCode();
}

1. equals(), 有如下要求
* Symmetry 对称性:如果x.equals(y)返回是“true”,那么y.equals(x)也应该返回是“true”。?
* Reflexivity反射性:x.equals(x)必须返回是“true”。?
* Transitivity传递性:如果x.equals(y)返回是“true”,而且y.equals(z)返回是“true”,那么z.equals(x)也应该返回是“true”。?
* Consistency一致性:如果x.equals(y)返回是“true”,只要x和y内容一直不变,不管你重复x.equals(y)多少次,返回都是“true”。?
* 还有就是x.equals(null),永远返回是“false”;x.equals(和x不同类型的对象)永远返回是“false”。

2. hashCode()的返回值和equals()的关系如下:
* 如果x.equals(y)返回“true”,那么x和y的hashCode()必须相等。?
* 如果x.equals(y)返回“false”,那么x和y的hashCode()有可能相等,也有可能不等。


关于hashCode到底怎么写最好, 关系到hash算法的原理, 算法导论中有详细论述,
Effective Java中也给出了一个指导意见

a. Compute an int hash code c for the field:
i. If the field is a boolean, compute (f ? 1 : 0).

ii. If the field is a byte, char, short, or int, compute (int) f.

iii. If the field is a long, compute (int) (f ^ (f >>> 32)).

iv. If the field is a float, compute Float.floatToIntBits(f).

v. If the field is a double, compute Double.doubleToLongBits(f), and
then hash the resulting long as in step 2.a.iii.

vi. If the field is an object reference and this class’s equals method
compares the field by recursively invoking equals, recursively
invoke hashCode on the field. If a more complex comparison is
required, compute a “canonical representation” for this field and
invoke hashCode on the canonical representation. If the value of the
field is null, return 0 (or some other constant, but 0 is traditional).

vii. If the field is an array, treat it as if each element were a separate field.
That is, compute a hash code for each significant element by applying
these rules recursively, and combine these values per step 2.b. If every
element in an array field is significant, you can use one of the
Arrays.hashCode methods added in release 1.5.

b. Combine the hash code c computed in step 2.a into result as follows:
result = 31 * result + c;

3. toString()
总可以由这个方法的返回值知晓对象的状态

发表评论
用户名: 匿名