java基础:Object的equals方法

一:看第一个例子

 

 

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
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));
}
}
 来自CODE的代码片
Object的equals方法

 

 

输出结果:

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方法

 

 

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
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));
}
 
}
 来自CODE的代码片
重写Obejct的equals方法
 
输出结果:
 
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;
    }
posted @ 2016-12-02 21:40  天涯海角路  阅读(162)  评论(0)    收藏  举报