/**
* 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)
*/
以上是对java中String类型数据的equals()方法的解释,翻译过来也就是:当且仅当对象不为空,且类型为String类型,并且有相同的字符串时,该方法返回true。
下面是该方法的源码:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
instanceof这个关键字是判断,参数类型是否为指定的类型String。
源码相对较为简答,判断思路就如同注释当中所说。
对于包装类来说都有equals这个方法,判断是有一个对象不为空很重要,当且仅当,所以要注意。
public class test {
public static void main(String[] args){
Integer a = null;
Integer b = null;
System.out.println(a.equals(b));
String str = null;
String str1 = null;
System.out.println(str.equals(str1));
}
}