java基礎:Object的equals方法

十五樓亮哥發表於2015-02-01

一:看第一個例子

public class Cat1 {
	private String color;
	private int height;
	private int weight;

	Cat1(String color, int height, int weight) {
		this.color = color;
		this.height = height;
		this.weight = weight;
	}
	public static void main(String[] args) {
		Cat1 cat1 = new Cat1("red", 1, 2);
		Cat1 cat2 = new Cat1("red", 1, 2);
		System.out.println(cat1 == cat2);
		System.out.println(cat1.equals(cat2));
	}
}

輸出結果:

false
false

cat1 == cat2 很簡單,他們不是同一物件,有不通的儲存地址。

但是cat1.equals(cat2)為什麼是false呢。因為cat是物件,這裡用的是父類的equals方法

而Object類equals方法的實現為:

<strong><span style="font-size:18px;"> public boolean equals(Object obj) {
        return (this == obj);
    }</span></strong>

所以,Obejct的equals方法本質上還是用==比較的。


二:嘗試重寫Obejct的equals方法


public class Cat2 {
	private String color;
	private int height;
	private int weight;

	Cat2(String color, int height, int weight) {
		this.color = color;
		this.height = height;
		this.weight = weight;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public int getWeight() {
		return weight;
	}

	public void setWeight(int weight) {
		this.weight = weight;
	}

	/**
	 * 重寫Object的equals方法
	 */
	public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		} else if (obj instanceof Cat2) {
			Cat2 catObj = (Cat2) obj;
			if (catObj.getColor() == this.color
					&& catObj.getHeight() == this.height
					&& catObj.getWeight() == this.weight) {
				return true;
			}

		}
		return false;
	}

	public static void main(String[] args) {
		Cat2 cat1 = new Cat2("red", 1, 2);
		Cat2 cat2 = new Cat2("red", 1, 2);
		System.out.println(cat1.equals(cat2));
	}

}

輸出結果:

true

三:String的equals方法

String s1 = "abc";
String s2 = "abc";
System.out.println(s1.equals(s2));

返回true,因為String就重寫了Object的equals方法
具體重寫實現為:

 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;
    }



相關文章