分类: Java
2006-11-16 21:48:28
equals()是Object类的一个方法,而Object是所有类的父类,因此实际上所有类都会继承到equals()方法。
equals()方法在java.lang.Object中的说明为:
public boolean equals(Object obj)
Indicates whether some other object is "equal to" this one.
The equals
method implements an equivalence relation:
It is reflexive: for any reference value x
, x.equals(x)
should return true
.
It is symmetric: for any reference values x
and y
, x.equals(y)
should return true
if and only if y.equals(x)
returns true
.
It is transitive: for any reference values x
, y
, and z
, if x.equals(y)
returns true
and y.equals(z)
returns true
, then x.equals(z)
should return true
.
It is consistent: for any reference values x
and y
, multiple invocations of x.equals(y) consistently return true
or consistently return false
, provided no information used in equals
comparisons on the object is modified.
For any non-null reference value x
, x.equals(null)
should return false
.
The equals method for class Object
implements the most discriminating possible equivalence relation on objects; that is, for any 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
).
其源码为:
public boolean equalss(Object obj) {
return (this = = obj);
}
由以上的注释可知Object中的equals()方法和 = =操作符是完成了相同的比较功能,都是对对象的引用进行了比较。
String类的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;
}
说明为:
public boolean equals(Object anObject)
Compares this string to the specified object. The result is true
if and only if the argument is not null
and is a String
object that represents the same sequence of characters as this object.
因此String中的equals()方法比较的是String对象中的内容,而不是它们的引用的值。