Java == 和 equals()

操作符 == 和!= 對於基本類型比較是其內容,但對於對象則是比較其引用。
方法 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

==================================================


這種結果其實也是根原於Java 對於對象的操作是使用對象的引用(還是別名問題)。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章