"=="和 equals 方法区别详解

Object类的equals方法

1)public boolean equals(Object obj) { return (this == obj); }提供定义对象是否“相等”的逻辑。

2)Object的equals方法定义为:x.equals(y)当x和y是“同一个”对象的应用时返回true否则返回false

3)J2SDK提供的一些类,如String,Date等,重写了Object的equals方法,调用这些类的equals方法,x.equals(y),当x和y所引用的对象是同一类对象且属性内容相等时(并不一定是相同对象),返回true否则返回false。

4)可以根据需要在用户自定义类型中重写equals方法。

知识链接:"=="和 equals 方法究竟有什么区别

==:运算符,适合于基本数据类型和引用数据类型。如果是基本数据类型,比较两个变量的值是否相等。 如果是引用数据类型变量,判断两个变量是否指向内存中的同一个对象(引用,内容都一样)。
equals():是 Object 类中定义过的一个方法。只适用于对象来调用。如果各个对象所在的类没有重写 Object 中的 equals(),则与==使用相同。如果所在的类重写了 equals(),一般重写的规则是判断两个对象中包含的所有属性的值是否相等。

/**
 * 说明:未重写equals方法时候
 * 如果各个对象所在的类没有重写 Object 中的 equals(),则与==使用相同。判断的是引用跟值都得相同
 * @author huayu
 * @date 2018/8/5 7:39 PM
 */
public class Dog {
    int color;
    int height,weight;

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

/**
 * 说明:equals方法的测试类
 *
 * @author huayu
 * @date 2018/8/5 7:41 PM
 */
public class TestEquals {
    public static void main(String[] args) {
        Dog dog=new Dog(1,2,3);
        Dog dog1=new Dog(1,2,3);
        System.out.println(dog==dog1);
        System.out.println(dog.equals(dog1));
    }
}

结果:
false
false
/**
 * 说明:重写equals方法时候
 * 如果所在的类重写了 equals(),一般重写的规则是判断两个对象中包含的所有属性的值是否相等。
 * @author huayu
 * @date 2018/8/5 7:39 PM
 */
public class Dog {
    int color;
    int height, weight;

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

    @Override
    public boolean equals(Object o) {
        if (o == null || getClass() != o.getClass()) {
            return false;
        } else {
            if (o instanceof Dog) {
                Dog dog = (Dog) o;
                if (dog.color == this.color && dog.height == this.height && dog.weight == this.weight) {
                    return true;
                }
            }
        }

        return false;
    }
}


/**
 * 说明:equals方法的测试类
 *
 * @author huayu
 * @date 2018/8/5 7:41 PM
 */
public class TestEquals {
    public static void main(String[] args) {
        Dog dog=new Dog(1,2,3);
        Dog dog1=new Dog(1,2,3);
        System.out.println(dog==dog1);
        System.out.println(dog.equals(dog1));

        //下面验证第三条String类是否真的重写了equals方法
        String string1=new String("hello");
        String string2=new String("hello");
        System.out.println("String判==结果:  "+(string1==string2));
        System.out.println("String判equals结果  "+(string1.equals(string2)));
    }
}

结果:
false
true
String判==结果:  false
String判equals结果:  true

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小猿架构

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值