Pages

2008/10/17

[Java] "equals()"與"=="

"=="是比較兩參考變數所儲存之值,
若該參考變數為基本資料型態, 會比較其存放之值是否相同, 相同則傳回true, 反之則傳回false.
若該參考變數為物件型態, 會比較該變數是否指向同一物件, 相同則傳回true, 反之則傳回false.

"equals()"為Java類別Object原有之函式, 繼承Object時可依據比較之內容及規則覆寫該方法,
若沒有覆寫equals(), 其比較條件如同"==".
JavaAPI有註明當覆寫equals()時, 必須覆寫hashCode(),
因當兩個物件相等時, 其hash code也必定會相等.
(若沒修改, JVM會隨機產生一組hash code)


public class Equivalence {
    public static void main(String[] args) {
    // 基本資料型態比較
        int i1 = 10;
        int i2 = 10;
        int i3 = 20;
        System.out.println("i1 == i2? " + (i1 == i2));
        System.out.println("i1 == i3? " + (i1 == i3));
        System.out.println();

        // 物件型態比較
        Integer i4 = 10;
        Integer i5 = 10;
        Integer i6 = new Integer(10);
        // 使用 "=="
        System.out.println("i4 == i5? " + (i4 == i5));
        System.out.println("i4 == i6? " + (i4 == i6));
        // 使用 "equals()", 類別Integer已將equals()覆寫
        System.out.println("i4.equals(i5)? " + i4.equals(i5));
        System.out.println("i4.equals(i6)? " + i4.equals(i6));
        System.out.println();

        A a1 = new A();
        A a2 = a1;
        A a3 = new A();
        // 使用 "=="
        System.out.println("a1 == a2? " + (a1 == a2));
        System.out.println("a1 == a3? " + (a1 == a3));
        // 使用 "equals()", 類別Integer已將equals()覆寫
        System.out.println("a1.equals(a2)? " + a1.equals(a2));
        System.out.println("a1.equals(a3)? " + a1.equals(a3));
        System.out.println();

        B b1 = new B();
        B b2 = b1;
        B b3 = new B();
        B b4 = new B();
        b4.s1 = "I'm b4.";
        // 使用 "=="
        System.out.println("b1 == b2? " + (b1 == b2));
        System.out.println("b1 == b3? " + (b1 == b3));
        System.out.println("b1 == b4? " + (b1 == b4));
        // 使用 "equals()", 類別Integer已將equals()覆寫
        System.out.println("b1.equals(b2)? " + b1.equals(b2));
        System.out.println("b1.equals(b3)? " + b1.equals(b3));
        System.out.println("b1.equals(b4)? " + b1.equals(b4));
    }
}

class A {
    public String s1 = "This is A's s1.";
}

class B {
    public String s1 = "This is B's s1.";
    public boolean equals(Object obj) {
    if( obj == null) return false;
    if( !(obj instanceof B)) return false;
    if( (this.s1 == ((B) obj).s1) & (this.hashCode() == ((B) obj).hashCode())) {
        return true;
    } else {
        return false;
    }
}
    public int hashCode() {
    return this.s1.length();
    }
}

結果:
i1 == i2? true
i1 == i3? false

i4 == i5? true
i4 == i6? false
i4.equals(i5)? true
i4.equals(i6)? true

a1 == a2? true
a1 == a3? false
a1.equals(a2)? true
a1.equals(a3)? false

b1 == b2? true
b1 == b3? false
b1 == b4? false
b1.equals(b2)? true
b1.equals(b3)? true
b1.equals(b4)? false

沒有留言: