首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Object种和String类的equals()和hashCode()方法

2012-12-25 
Object类和String类的equals()和hashCode()方法Object类equals方法:The equals method for class Object i

Object类和String类的equals()和hashCode()方法

Object类

equals方法:

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

?

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

?

这个方法提供了最严格的对象上的等价关系;对于非空的对象引用x和y,equals方法返回true,当且仅当x和y指向同一个对象的时候。

?

注意为了保持equals对象必须有相同的哈希码的特性,通常重载equals方法的时候有必要重载hashCode方法。

?

hashCode方法:

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results.

?

如果两个对象具有equsals关系,那么两个对象的hashCode值一定相等;但是如果两个对象不具有equsals关系,不一定这两个对象的hashCode值就不相等。

?

?

String类重载了Object类的equals方法和hashCode方法:

如果两个字符串对象中的字符个数,相对应位置的字符相同,那么这两个字符串对象具有equals关系。

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;
??? }

?

如果两个字符串具有equals关系,那么这两个字符串的hashCode值一定相等。

public int hashCode() {
?int h = hash;
?if (h == 0) {
???? int off = offset;
???? char val[] = value;
???? int len = count;

??????????? for (int i = 0; i < len; i++) {
??????????????? h = 31*h + val[off++];
??????????? }
??????????? hash = h;
??????? }
??????? return h;
??? }

?

?

?

?

?

?

热点排行