String重写的Equals

一、"==" 与 equals

下边这段代码应该都看过或者写过:

String str1 = "test";
String str2 = "test";
		
String str3 = new String("test");
String str4 = new String("test");
		
System.out.println(str1 == str2);//true
System.out.println(str1.equals(str2));//true
System.out.println(str3 == str4);//false
System.out.println(str3.equals(str4));//true

由于 "==" 进行值比较,则在str1与str2比较为true,而在new String 的str3与str4为false,虽然equals进行的是引用比较,但String中将equals方法重写,来达到进行比较字符串中的值比较。

二、String中的equals

先看源码:

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;
}

源码注释中写道:Compares this string to the specified object.  The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

翻译:将此字符串与指定的对象进行比较。当且仅当参数不为空并且是表示与此对象相同的字符序列的字符串对象时,结果为真。

看代码就是逐个对比两个字符串序列,比如下边图中红框内的判断条件:

1、while循环体内:当字符序列其中某个字符与比较字符不相同是返回false;

2、结束循环,对比结束无不相同的情况,返回true;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值