== :它的作用是判断两个对象的地址是不是相等。即:判断两个对象是不是同一个对象(基本数据类型比较的是值,引用数据类型比较的是内存地址)。
equals() :它的作用也是判断两个对象是否相等。但它一般有两种使用情况:
- 情况 1:类没有覆盖 equals() 方法。则通过 equals() 比较该类的两个对象时,等价于通过 ”==“ 比较这两个对象。
// Object类中的equals() 方法
public boolean equals(Object obj) {
return (this == obj);
}
- 情况 2:类覆盖了 equals() 方法。一般,我们都覆盖 equals() 方法来比较两个对象的内容是否相等;若他们的内容相等,则返回true(即,认为这两个对象相等)。
/**
* String类中的equals() 方法,已覆盖,用于比较内容
* 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;
}
举个例子:
public class test1 {
public static void main(String[] args){
String a = new String("ab"); // a为一个引用
String b = new String("ab"); // b为另一个引用,对象的内容一样
String aa = "ab"; // 放在常量池中
String bb = "ab"; // 从常量池中查找
if(aa == bb) // true
System.out.println("aa==bb");
if(a == b) // false,非同一对象
System.out.println("a==b");
if(a.equals(b)) // true
System.out.println("aEQb");
if(42 == 42.0) { // true
System.out.println("true");
}
}
}
结果:
说明:
- String 中的 equals 方法是被重写过的,因为 object 的 equals 方法是比较对象的内存地址,而 String 的 equals 方法比较的是对象的值。
- 当创建 String 的类型的对象时,虚拟机会在常量池中查找有没有已经存在的值和要创建的值相同的对象,如果有就把它赋给当前引用。如果没有就在常量池汇总重新创建一个 String 对象。