源码:
java.lang.Object.equals()方法:
-------------------------------------------------------------
public boolean equalss(Object obj) {
return (this = = obj);
}
-------------------------------------------------------------
jdk文档中给出如下解释:
-------------------------------------------------------------
The equalss method implements an equivalence relation:
? It is reflexive: for any reference value x, x.equalss(x) should return true.
? It is symmetric: for any reference values x and y, x.equalss(y) should return true if and only if y.equalss(x) returns true.
? It is transitive: for any reference values x, y, and z, if x.equalss(y) returns true and y.equalss(z) returns true, then x.equalss(z) should return true.
? It is consistent: for any reference values x and y, multiple invocations of x.equalss(y) consistently return true or consistently return false, provided no information used in equalss comparisons on the object is modified.
? For any non-null reference value x, x.equalss(null) should return false.
The equalss 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).
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 equals objects must have equals hash codes.
-------------------------------------------------------------
由以上的注释可知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;
}
-------------------------------------------------------------
此方法的注释为:
-------------------------------------------------------------
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类的equal方法是对对象的值进行比较。
根据以上的讨论可以得出结论:equal方法和= =操作符是否存在区别要个别对待,要根据equal的每个实现情况来具体判断。
*******************************
belter(belter@sina.com)
none.blogdriver.com
文章来源于领测软件测试网 https://www.ltesting.net/