加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么String.equals中有“==”?

发布时间:2020-12-15 05:13:08 所属栏目:Java 来源:网络整理
导读:为什么 Java在equalsIgnoreCase方法中比较(this ==另一个String)来检查字符串不敏感? 另外,String equals是比较(this ==另一个String)来比较两个对象? Java 6:下面给出的String类equalsIgnoreCase实现. public boolean equalsIgnoreCase(String anotherSt
为什么 Java在equalsIgnoreCase方法中比较(this ==另一个String)来检查字符串不敏感?

另外,String equals是比较(this ==另一个String)来比较两个对象?

Java 6:下面给出的String类equalsIgnoreCase实现.

public boolean equalsIgnoreCase(String anotherString) {
        return (this == anotherString) ? true :
               (anotherString != null) && (anotherString.count == count) &&
           regionMatches(true,anotherString,count);
    }

Java 6:String Class等于下面给出的实现.

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }

解决方法

Why Java is comparing (this == another String) inside equalsIgnoreCase method for checking a string insensitive?

这是一个优化.如果传入的引用与此完全相同,则equals必须返回true,但我们不需要查看任何字段等.一切都与它自身相同.从Object.equals(Object)的文档:

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x,x.equals(x) should return true.

平等检查通常以:

>另一个参考是否等于此?如果是这样,返回true.
>另一个引用是否为null?如果是,则返回false.
>另一个引用是否引用了错误类型的对象?如果是,则返回false.

然后你继续进行特定类型的检查.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读