在Object 類中定義有:
1、public boolean equals(Object object )方法提供定義對象是否“相等”邏輯。
2、Object的equals方法定義為:x.equals(y)當x和y是同一個對象的引用時,返回true,否則返回false
3、在其他一些類中,例如String Date等,重寫了Object的equals方法,調用這些類的equals方法,當x和y所引用的對象是同一類對象且屬性內容相等時
(并不一定是相同對象),return true;?否則的話,return false;
4、當然,可以根據需要在用戶自己定義重寫equal方法。
舉例:
public class TestEquals{
????public? static void main(String[] args) {
????????????????Cat c1 = new Cat(1,2,3);
????????????????Cat c2 = new Cat(1,2,3);
????????????????System.out.println(c1 == c2);//false
????????????????System.out.println(c1.equals(c2));//true
????????}
????}
????class Cat{
????????int color;
????????int height,weight;
????????public Cat(int color, int height, int weight){
????????????this.color = color;
????????????this.height = height;
????????????this.weight = weight;
????????}
????public boolean equals?(Object obj){
????????if(obj == null) return false;
????????else{
????????????if(obj instanceof Cat){/*if obj is? a object of Cat ,return true ,else if obj is not a object of Cat or is null,return flase*/
????????????Cat c = (Cat)obj;
????????????if(c.color == this.color && c.height == this.height && c.weight == this.weight)
????????????return true;
????????????}
????????}
????}
return false;
}
運行結果:
false
????? ?true