方法 equals() 不適用於基本類型的比較,適合對象之間的比較。但其默認行爲也是比較對象的引用。
Java 類庫中大多數都實現了equals() 方法,來比較對象之間的內容,而不是比較對象的引用。
class Test {
int value;
}
public class Operator {
public static void main(String[] args) {
int i1 = 10;
int i2 = 10;
System.out.println("基本數據類型比較, i1 == i2 ?: " + (i1 == i2));
Integer n1 = new Integer(10);
Integer n2 = new Integer(10);
System.out.println("基本數據類型Integer對象比較, n1 == n2 ?: " + (n1 == n2));
Test t1 = new Test();
Test t2 = new Test();
t1.value = t2.value = 10;
System.out.println("自定義類對象比較, t1 == t2 ?: " + (t1 == t2));
String s1 = new String("aaa");
String s2 = new String("aaa");
System.out.println("已實現 equals()方法對象的比較, s1 == s2 ?: " + s1.equals(s2));
}
}
比較對象,預期結果都是 False, 實現了equals() 方法後,比較結果爲True
==================================================
基本數據類型比較, i1 == i2 ?: true基本數據類型Integer對象比較, n1 == n2 ?: false
自定義類對象比較, t1 == t2 ?: false
已實現 equals()方法對象的比較, s1 == s2 ?: true
==================================================