开发日常小结(34):源码分析:String类的equals()方法

本文详细解析了Java中String类的equals方法实现原理,通过源码分析,解释了equals方法如何比较两个字符串对象的内容,而非内存地址。并通过一个测试Demo展示了equals与==操作符的区别。

目录

1、提出问题

2、源码分析

3、测试Demo:


1、提出问题

我们都知道,在Java中,“==”比较的是对象在内存中的地址,“equals”比较对象的内容;今天复习一下”equals“。

 

2、源码分析

    /**
     * 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) {
        //First:比较两个对象是否是同一个对象,则直接return true;
        if (this == anObject) {
            return true;
        }

        //Second:如果被比较的对象是String类型,则继续
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            
            //Third:比较两者的长度
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;

                //Forth:比较两者元素是否相同
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

 

3、测试Demo:


public class test_equals {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 String a="1234";
         String b="1234";
         String c = new String("1234");
         System.out.println("a==b: "+(a==b));
         System.out.println("a==c: "+(a==c));
         System.out.println("a.equals(c): "+(a.equals(c)));
	}

}

console:

a==b: true
a==c: false
a.equals(c): true

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

后台技术汇

对你的帮助,是对我的最好鼓励。

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

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

打赏作者

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

抵扣说明:

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

余额充值