概括的讲,他们两个用于判断两个数据是否相等的问题,但是他们两个也有不同之处。
- 了解 ==
- 了解equals
- String的equals源码
了解 ==
- 比较基本数据类型(byte、short、int、long、float、double、char、boolean)时,需要用 == ,比较的是它们的值是否相等;
- 比较引用数据类型时,用 == 比较的是它们的内存地址。
了解 equals
- equals方法不能作用于基本数据类型的变量
- equals一般用来比较对象的内存地址。但是对于String、Integer、Date等覆盖了equals()方法的类型,而equals()的结果则由覆盖后的代码决定。
String的equals源码
String的queals比较的是String值相等不相等。附:String的equals的源码(首先判断参数是不是自己==>判断参数是不是String类型的==>判断长度==>将这两个转化为字符数组,进行 == 比较)
/**
* 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)
*/
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;
}