zoukankan      html  css  js  c++  java
  • String类的equal方法

    先来看这个方法的英文注释

    /**
         * 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)
         */

    英文不好的同学不用担心,让我用自己蹩脚的英文翻译下。

    这个方法用来对比当前字符串和指定对象是否相等。当且仅当指定对象当前字符串拥有的相同字符序列时,这个方法才返回true。

    接着我们再来看下这个方法的源码:

    public boolean equals(Object anObject) {
           //如果是同一个对象(内存地址一样),则直接返回true
            if (this == anObject) {
                return true;
            }
           /*判断指定对象是否为字符串类型,不是的话直接返回false;
           是字符串类型类型的话,将当前字符串和指定对象转换为对 
           应的字符数组,然后通过while循环遍历两个相同位置的字符数组元素是否相同,只要有一个不同则直接返回false;否则返回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;
        }

    是不是很简单哈!

    你想拥有什么,你就去追求什么!
  • 相关阅读:
    Kubernetes(k8s)1.12.2集群搭建
    Drools规则引擎入门指南(三)——使用Docker部署Workbench
    Drools规则引擎入门指南(二)
    网络协议 11
    网络协议 10
    网络协议 9
    网络协议 8
    网络协议 7
    网络协议 6
    网络协议 5
  • 原文地址:https://www.cnblogs.com/lchzlp/p/13096302.html
Copyright © 2011-2022 走看看