读书人

关于一段代码的不解

发布时间: 2012-10-06 17:34:01 作者: rapoo

关于一段代码的疑惑

今天需要写一段关于输入字符串的check的代码,突然想到equalIrgoreCase貌似功能上比equals更强大,但是为啥很多时候都只用equals 而不用equalIrgoreCase呢?所以就去看了下源代码,结果发现了String类中的一点额外的东西。

?

源代码如下:

 /**     * Compares this string to the specified {@code CharSequence}.  The result     * is {@code true} if and only if this {@code String} represents the same     * sequence of char values as the specified sequence.     *     * @param  cs     *         The sequence to compare this {@code String} against     *     * @return  {@code true} if this {@code String} represents the same     *          sequence of char values as the specified sequence, {@code     *          false} otherwise     *     * @since  1.5     */    public boolean contentEquals(CharSequence cs) {        if (count != cs.length())            return false;        // Argument is a StringBuffer, StringBuilder        if (cs instanceof AbstractStringBuilder) {            char v1[] = value;            char v2[] = ((AbstractStringBuilder)cs).getValue();            int i = offset;            int j = 0;            int n = count;            while (n-- != 0) {                if (v1[i++] != v2[j++])                    return false;            }        }        // Argument is a String        if (cs.equals(this))            return true;        // Argument is a generic CharSequence        char v1[] = value;        int i = offset;        int j = 0;        int n = count;        while (n-- != 0) {            if (v1[i++] != cs.charAt(j++))                return false;        }        return true;    }

? 我很想知道为什么当

 if (cs instanceof AbstractStringBuilder){     ...}

?成立的时候,为啥结尾不直接返回true呢?如果传入的参数是一个StringBuffer or StringBuilder,则需要遍历两次,这是为什么呢?我感觉添加一个return true 更合理一些,不是吗?如:

 // Argument is a StringBuffer, StringBuilder        if (cs instanceof AbstractStringBuilder) {            char v1[] = value;            char v2[] = ((AbstractStringBuilder)cs).getValue();            int i = offset;            int j = 0;            int n = count;            while (n-- != 0) {                if (v1[i++] != v2[j++])                    return false;            }        return true;        }
?

读书人网 >编程

热点推荐