Java-20,object类之equals方法

equals方法

  • Object类中定义有:
    • public boolean equals(Object obj)方法
      • 提供定义对象是否“相等”的逻辑
    • Object的equals方法定义为:x.equals(y) 当x 和 y 是同一对象的应用时返回true 否则返回 false
    • J2SDK提供的一些类,如String,Date等,重写了Object的equals方法,调用这些类的equals方法,x.equals(y),当x和y所引用的对象是同一类对象且属性内容相等时(并不一定是相同对象),返回true否则返回false
    • 可以根据需要在用户自定义类型中重写equals方法。

示例:

package com.nyist;

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);
     System.out.println(c1.equals(c2));

     } }
class Cat{ int color; int height,weight; public Cat(int color,int height,int weight) { this.color = color; this.height = height; this.weight = weight; } }

结果:

false
false

equals方法的默认实现和==是一样的,都是比较是否是同一引用。

通过重写可以实现只比较两对象是否实质是一样的。

示例:

package com.nyist;

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.equals(c2));
    }
}

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) {
                Cat c = (Cat)obj;
                if(c.color == this.color && c.height ==this.height && c.weight == this.weight)
                    return true;
            }
        }
        return false;
    }
}

结果:

true

猜你喜欢

转载自www.cnblogs.com/nyist0/p/12449526.html