== 和 equals的联系与区别

在以前刚开始了解这两个的时候,只是粗浅的知道比较基本类型等数据的时候可以用==,但在比较两个字符串的时候,就得用equals进行比较,以前不太明白其中的原理,最近偶然一次机会对这个有个更深的理解。

  1. 为什么要区分==和equals
    我们所说的两个字符串是否相等,是指字符串字面量是否相等,如果使用==来判断两个字符串是否相等,那么实际比较的是两个字符串的**存储地址(即内存地址)**是否相等,因此就容易产生以下问题
String str3 = "hello";
String str4 =str3+"";
System.out.println(str3 == str4);

在这里插入图片描述
两个String的内容相同,但因为地址指向不同,从而导致结果为false,这时候就得用到equals方法了。

  1. 关于equals方法的一些实现
    真正Object类里面的equals方法其实跟==一样,甚至它就是用==来实现的,下面是Object类里面的equals方法:
    public boolean equals(Object obj) {
        return (this == obj);
    }

所以如果我们使用未重写的equals类,跟直接用==效果是一样的。因此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方法就可以起到对比对象值的作用,想要它起到这个作用,就必须重写equals方法,在自己创建的类里面也是如此。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值