equals与==的区别


equals与==的区别


一、==的功能是什么?

解释:== 是用于比较内存地址的。当比较对象的引用类型是,比较内存地址是否一致,从而判断对象是否相同;当比较的是基本类型的数值时,也是比较其数值存放的内存地址是否相同,数值相同的内存地址是相同的。所以总结可得==的本质就是内存地址的比较。

二、equals()的功能

1.原有功能:

equals()是Object类中的一个判断对象是否相同的方法,也就是在Object中和==是一样的功能,比较对象实例的内存地址是否相同;

2.大多数类重写后的功能(如String):

下面是String类中重写的equals(),大致就是对传入的比较参数进行字符的对比,比较字符串的内容是否一致,形成新的比较字符内容的功能,符合实际开发中的需要。重写后就是比较内容是否相同,常见的这些引用类型都已经重写了该方法,如果自己定义的类需要比较对象的内容是否一致,可以自己在声明类中重写达到需要的功能。

/**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
    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;
    }

总结

以上的内容就是个人对==和equals()的一些理解,有什么不对的希望可以留言评论,共同探讨

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

等待出口的递归

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

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

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

打赏作者

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

抵扣说明:

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

余额充值